开发者

Why NullPointerException when programmatically add my text view?

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.setOrienta开发者_Go百科tion(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?

P.S. (Update)

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);


Problem is in this line

 TextView nameField = (TextView)findViewById(R.id.name_text);

.See there is a mismatch with the spelling in the layout file.and also assure setContentView(R.layout.main);I ran your code.It runs fine.


You haven't called setContentView(...) with a layout file. It sounds like what you may want to do is create the 10 views in code and apply some styling to them instead.

You can't access these 10 view with findViewById(...) as your layout file only specifies one view. You could also import that layout 10 times into a main layout file with the LinearLayout defined as the parent view.


Look at this Link the checkbox . What you're doing is create a layout dynamically and with an xml, just choose one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜