如何在Android上的对话框中设置View

时间:2013-04-24 02:43:11

标签: android dialog

我使用下面的代码在对话框中设置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中的T​​extView 但它在行MyTextView.setText("test");处发生NullPointer错误 我怎么修改它?

1 个答案:

答案 0 :(得分:2)

当您实例化“MyTextView”时,您应该使用以下代码进行实例化:

TextView MyTextView = (TextView)layout.findViewById(R.id.my_tv);