Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to dynamically add a TextView to a ScrollView crashes when using an XML layout

Tags:

android

This is a very simple example where I have a single ScrollView defined in R.layout.main. Then I try to dynamically add a TextView to it.

Unfortunately this crashes.

ScrollView scroll = (ScrollView) this.findViewById(R.id.scrollView1);

TextView tv1 = new TextView(this);
tv1.setText("This is tv1");

scroll.addView(tv1);

setContentView(R.layout.main);

Now I can do something like this:

ScrollView scroll = new ScrollView(this);
TextView tv1 = new TextView(this);
tv1.setText("This is tv1");

scroll.addView(tv1);

setContentView(scroll);

But I'd really like to be able to define some base UI elements in XML, then dynamically add others.

What's the best way to do that?

like image 891
Mark Biek Avatar asked Feb 17 '11 13:02

Mark Biek


5 Answers

That is because you are trying to access a view which hasn't been parsed by Android yet.

When you define a layout using XML, then you have to call setContentView first, passing it the layout file reference so that Android can parse the file. Only then you can access the elements using findViewById.

That basically means that you should call setContentView before trying to access any element of your layout.

like image 100
Octavian A. Damiean Avatar answered Nov 09 '22 07:11

Octavian A. Damiean


You must call setContentView before you doing anything else with any views.

This should work.

setContentView(R.layout.main);
ScrollView scroll = (ScrollView) this.findViewById(R.id.scrollView1);

TextView tv1 = new TextView(this);
tv1.setText("This is tv1");

scroll.addView(tv1);
like image 36
Robby Pond Avatar answered Nov 09 '22 05:11

Robby Pond


Another way to do this,

You can create a new LinearLayout inside the ScrollView, and set the id as say, layoutinside

now

setContentView(R.layout.main);

 LinearLayout ll = (LinearLayout) findViewById(R.id.layoutinside);
 TextView tv1 = new TextView(this);
 tv1.setText("This is tv1");

 ll.addView(tv1);

This is working fine for me

like image 37
Vishnu Avatar answered Nov 09 '22 05:11

Vishnu


findViewById should only be called after you have called setContentView(R.layout.main);. Currently scroll will be null so I would expect it to throw a NullPointerException at scroll.addView(tv1);

like image 1
dave.c Avatar answered Nov 09 '22 06:11

dave.c


i Got your problem . You need to set the contentView as like this before

setContentView(R.layout.main);

ScrollView scroll = (ScrollView) this.findViewById(R.id.scrollView1);

TextView tv1 = new TextView(this);
tv1.setText("This is tv1");

scroll.addView(tv1);
like image 1
Rohit Sharma Avatar answered Nov 09 '22 07:11

Rohit Sharma