I programmatically created a linear layout in my Activity like the following:
LinearLayout myContent = new LinearLayout(this);
myContent.setOrientation(LinearLayout.VERTICAL);
Then, I defined a text view in xml (under res/layout/) like below:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/name_text"
android:layout_width="80dp"
android:layout_height="40dp"
android:gravity="center"
/>
After that, I would like to add several TextView
defined above to myContent
linear layout programmatically like below:
//my content is a linear layout
LinearLayout myContent = new LinearLayout(this);
myContent.setOrientation(LinearLayout.VERTICAL);
for(int i=0; i<10; i++){
//get my text view resource
TextView nameField = (TextView)findViewById(R.id.name_text);
nameField.setText("name: "+Integer.toString(i)); //NullPointerException here
}
myContent.addView();
I thought the above code should add 10 TextView
with name into myContent
linear layout. But I end up with a NullPointerException at nameField.setText(...);
(see above code) Why?
myContent
Linear Layout is added to another linear layout which is defined in main.xml, and my activity has setContentView(R.layout.main)
If your R.id.name_text is in another layout, you have to inflate that layout and then attach it,
because when you refer to R.id.name_text, it cannot be found because your layout is not present unless its inflated.
e.g.
View child = getLayoutInflater().inflate(R.layout.child);
myContent.addView(child);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With