为什么在以编程方式添加文本视图时出现NullPointerException?

Mel*_*lon 4 android android-widget android-manifest android-emulator android-layout

我在我的Activity中以编程方式创建了一个线性布局,如下所示:

LinearLayout myContent = new LinearLayout(this);
myContent.setOrientation(LinearLayout.VERTICAL);
Run Code Online (Sandbox Code Playgroud)

然后,我在xml(在res/layout /下)定义了一个文本视图,如下所示:

<?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"
/>
Run Code Online (Sandbox Code Playgroud)

在那之后,我想以编程方式TextView将以上定义的几个添加到myContent线性布局,如下所示:

//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();
Run Code Online (Sandbox Code Playgroud)

我认为上面的代码应该将10 TextView名称添加到myContent线性布局中.但是,我结束了一个NullPointerException异常nameField.setText(...);(见上面的代码),为什么呢?

PS(更新)

myContent线性布局添加到另一个在main.xml中定义的线性布局,我的活动 setContentView(R.layout.main)

sat*_*sat 6

如果你的R.id.name_text在另一个布局中,你必须膨胀该布局然后附加它,
因为当你引用R.id.name_text时,它找不到它,因为你的布局不存在,除非它膨胀.

例如

查看child = getLayoutInflater().inflate(R.layout.child);
myContent.addView(孩子);