【发布时间】:2015-02-14 09:09:11
【问题描述】:
我有一个要用来配置小部件的活动,但我似乎无法让findViewById() 工作。它为所有元素返回null。
这是我的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:name="@+id/testTextView"
android:text="refresh time (seconds)"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:name="@+id/testEditText"
android:text="10"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" />
<Button
android:name="@+id/testButton"
android:text="Button text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
这是我的活动的 onCreate 方法:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configure_widget);
Button button = (Button) findViewById(R.id.testButton);
EditText editText = (EditText) findViewById(R.id.testEditText);
TextView textView = (TextView ) findViewById(R.id.testTextView);
button.setText("Button test");
editText.setText("editText test");
textView.setText("textView test");
}
每个元素(按钮、editText、textView)都是null,当我尝试设置文本时它会抛出NullPointerException。如果我注释掉这些 setText 行,则会显示 xml 中定义的正确布局。
虽然如果我使用View v = findViewById(android.R.id.content); 来获取根元素并从中获取子元素,它会起作用。
像这样:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configure_widget);
View v = findViewById(android.R.id.content); //this is a FrameLayout, I don't know if the container is always a framelayout
ViewGroup firstChild = (ViewGroup)((ViewGroup)v).getChildAt(0); //this gets my linearlayout
TextView textView = (TextView)(firstChild.getChildAt(0));
EditText editText = (EditText)(firstChild.getChildAt(1));
Button button = (Button)(firstChild.getChildAt(2));
button.setText("Button test");
editText.setText("editText test");
textView.setText("textView test");
}
使用此布局,每个元素的文本都按预期设置为“Button test”、“editText test”和“textView test”。
我已经清理并重建了项目。在调试时,我检查了资源名称实际上是否解析为 id 号。
谁能解释发生了什么?为什么我的findViewById() 不为我工作?
【问题讨论】: