【发布时间】:2014-12-01 00:12:18
【问题描述】:
在下面的代码中,我尝试在单击按钮时显示一个基本对话框。该对话框显示一些需要显示一些文本。在我偶然发现一个错误后,我已经让它工作了,但我仍然对为什么会发生这个错误有疑问。 在 DialogFragmentSubclass.onCreateView() 中,我通过调用 findViewById(R.id.someIdValue) 获得对 TextView 的引用。这给了我 NullPointerException。但是,通过调用获取参考:
View v = inflate.inflate(someREsourceValue, container, fals);
TextView tv = (TextView) v.findViewById(R.id.someValue);
似乎可以解决问题。为什么这行得通,而另一个给我一个 NullPointerException? (完整代码见下文)
public class MainActivity extends Activity {
DownloadImageDialogFragment myDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
// get reference to buttons
Button buttonDownloadImage = (Button) findViewById(R.id.downloadImage);
buttonDownloadImage.setText("Download new Image");
// upon button click, show a Dialog
buttonDownloadImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentTransaction ft = getFragmentManager().beginTransaction();
myDialog = new DownloadImageDialogFragment();
myDialog.show(ft, null);
}
});
}
private class DownloadImageDialogFragment extends DialogFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dialog, container, false);
// TextView tv = findViewById(R.id.dialogTextView); // this gives an error
TextView tv = (TextView) v.findViewById(R.id.dialogTextView); // this works
tv.setText("This is my dialog");
return v;
}
}
}
这里是对话框的布局文件:
<TextView
android:id="@+id/dialogTextView"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</LinearLayout>
【问题讨论】:
-
Fragment 只是一个 View 的占位符,您首先需要为 View 充气然后使用它。
标签: android view nullpointerexception findviewbyid dialogfragment