我使用下面的代码在对话框中设置View:
LayoutInflater inflater = LayoutInflater.from(this);
View layout = inflater.inflate(R.layout.mylayout, null);
TextView MyTextView = (TextView)findViewById(R.id.my_tv);
MyTextView.setText("test");
AlertDialog MyDialog;
AlertDialog.Builder MyBuilder = new AlertDialog.Builder(this);
MyBuilder.setTitle("title");
MyBuilder.setView(layout);
MyDialog = MyBuilder.create();
MyDialog.show();
my_tv是mylayout.xml中的TextView
但它在行MyTextView.setText("test");
处发生NullPointer错误
我怎么修改它?
答案 0 :(得分:2)
当您实例化“MyTextView”时,您应该使用以下代码进行实例化:
TextView MyTextView = (TextView)layout.findViewById(R.id.my_tv);