我是 android 开发的初学者,希望得到以下解释,
我正在尝试在自定义对话框中获取用户输入。下面的代码有效。但是如果我更换
final EditText editText = (EditText) view.findViewById(R.id.editText);
与
final EditText editText = (EditText) getActivity().findViewById(R.id.editText);
我在 setPositiveButton() 的 getText() 语句中得到 nullPointerException。
此外,任何关于为什么我在声明时但在阅读文本 (getText()) 时没有出错的解释都将不胜感激。
public class FireMissilesDialogFragment extends DialogFragment{
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View view = layoutInflater.inflate(R.layout.edit_menu, null);
final EditText editText = (EditText) view.findViewById(R.id.editText);
builder.setView(view)
.setMessage("Fire food missile?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), editText.getText().toString(), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), "Why not?", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
最佳答案
i get nullPointerException at getText() statement in setPositiveButton().
In addition, any explanation of why i don't get error while declaring but while reading the text (getText()) would be appreciated
findViewById
在第二种情况下返回 null,因为您要查找的小部件 TextView
属于您扩充并设置为对话框 View 的布局而不是 Activity
的 Activity 。由于返回的引用为 null,当您尝试访问其成员之一时,getText()
在这种情况下,将抛出 NullPointerException
关于android - 需要解释 : getText() throws error on getActitvity()ut not on view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31733267/