【问题标题】:NullPointerException while changing textView text in an AlertDialog在 AlertDialog 中更改 textView 文本时出现 NullPointerException
【发布时间】:2014-08-18 12:25:11
【问题描述】:

背景:

  • 我只想创建一个具有特定布局的 customDialog 并添加内容。
  • 它是一个 DialogFragment

代码:

TextView text;

@Override
public void onCreate(Bundle savedInstanceState){
 super.onCreate(savedInstanceState);

 text = (TextView)getView().findViewById(R.id.lorem);
 text.setText("Test");
}


@Override
public Dialog onCreateDialog(Bundle savedInstanceState){

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
 LayoutInflater inflater = getActivity().getLayoutInflater();
 builder.setView(inflater.inflate(R.layout.custom_dialog, null));
 return builder.create();
}

问题:

  • 对话框有效,但在我开始在“onCreate”中添加这些行后,我收到了 NullPointerException 错误。我希望有人可以帮助我。

感谢@Raghunandan 的回答+解释,这是工作代码:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){

     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
     LayoutInflater inflater = getActivity().getLayoutInflater();
     View view = inflater.inflate(R.layout.custom_dialog_style, null);
     textView = (TextView)view.findViewById(R.id.your_textview);
     textView.setText("Test");
     builder.setView(view);
     return builder.create();
    }

【问题讨论】:

  • 使用SetContentView而不是setView
  • @QadirHussain 这是一个DialogFragment
  • @vyn 使用视图对象来初始化您的视图。删除onCreate中的代码

标签: android nullpointerexception dialog textview customdialog


【解决方案1】:

起初我以为是Activity,现在我看到了DialogFragment

我猜这个视图属于custom_dialog.xml

View view = inflater.inflate(R.layout.custom_dialog, null);
text = (TextView)view.findViewById(R.id.lorem); 
builder.setView(view);

所以使用视图对象来初始化TextView

text = (TextView)getView().findViewById(R.id.lorem); 这里getView() 返回空值。

您在 null 上调用 setText,导致 NullPointerException

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-19
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    相关资源
    最近更新 更多