我有一个从Activity调用的LoginDialog。在LoginDialog中,我试图打开另一个Dialog(mProgressDlg)来指示进度。在mProgressDlg布局中我有2个TextView。我NullPointerException
setText()
TextView
private Dialog mProgressDlg;
private TextView mMessage, mprogTitle, mProgMessage;
public LoginDialog(Context context) {
super(context);
mContext = context;
ld = null;
init();
}
private void init() {
this.setContentView(R.layout.user_pass_dialog);
mMessage = (TextView) findViewById(R.id.messageText);
mMessage.setText("Loaded ");
// ProgressDialog
mProgressDlg = new Dialog(mContext);
mProgressDlg.setContentView(R.layout.progress_dialog);
mProgTitle = (TextView) findViewById(R.id.titleText_progressDlg);
mProgMessage = (TextView) findViewById(R.id.message_progressDlg);
// On below 2 lines, I get NPE.
mProgTitle.setText("Hello");
mProgMessage.setText("Good Day");
}
。
LoginDialog:
<TextView android:id="@+id/titleText_progressDlg" android:text="TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginTop="10dp" android:textStyle="bold"></TextView>
<TextView android:id="@+id/message_progressDlg" android:text="TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginTop="10dp"></TextView>
progressDialog.xml
04-06 14:54:29.087: ERROR/AndroidRuntime(379): Caused by: java.lang.NullPointerException
04-06 14:54:29.087: ERROR/AndroidRuntime(379): at orange.android.vpn.LoginDialog.init(LoginDialog.java:88) ***// THIS IS mProgTitle.setText("Hello");***
04-06 14:54:29.087: ERROR/AndroidRuntime(379): at orange.android.vpn.LoginDialog.<init>(LoginDialog.java:50) ***// THIS IS CALLING init() FROM CONSTRUCTOR***
LogCat:
NullPointerException
任何人都可以帮助我知道,为什么我在访问init()
和/或mProgTitle
时会在{{1}}中收到此mProgMessage
。任何帮助都非常感谢。
由于
答案 0 :(得分:2)
mProgressDlg.setContentView(R.layout.progress_dialog);
mProgTitle = (TextView) findViewById(R.id.titleText_progressDlg);
应该是
mProgressDlg.setContentView(R.layout.progress_dialog);
mProgTitle = (TextView) mProgressDlg.findViewById(R.id.titleText_progressDlg);
因为您正在访问对话框布局中的组件。 findViewById用作活动中的函数,因为你:使用setContentView({layout})设置活动的布局并使用findViewById访问组件,对于你输入dialog.setContentView的对话框也一样,你可以访问samo diloag.findViewById组件