我使用 AlertDialog.Builder 类创建了一个对话框,并调用 builder.setView(int resource) 为其提供文本输入的自定义布局。
当用户点击“确定”时,我试图从布局上的 EditText 检索值,但是当调用 findViewByID() 时,我得到空引用。阅读周围的内容后发现,如果在调用 setContentView() 之前尝试加载视图,这种情况就会发生在其他地方。对于生成器,我显然还没有这样做,有没有办法检索视图,或者我应该以不同的方式构建我的对话框?
Java 和堆栈跟踪如下:
// Set up the on click of the Button
Button add = (Button) findViewById(R.id.manage_connections_add_button);
add.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ManageConnectedServicesActivity.this);
builder.setTitle("Add Service");
builder.setView(R.layout.component_sharing_service_dialogue);
// Set up the buttons on the dialog
builder.setPositiveButton("Add", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Get the connected service url
EditText url = (EditText) findViewById(R.id.add_sharing_service_url); // This is the offending line
addConnectedService(url.getText().toString()); // Crashes here
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
});
堆栈跟踪:
12-05 09:54:40.825 1889-1889/uk.mrshll.matt.accountabilityscrapbook E/AndroidRuntime: FATAL EXCEPTION: main
Process: uk.mrshll.matt.accountabilityscrapbook, PID: 1889
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at uk.mrshll.matt.accountabilityscrapbook.ManageConnectedServicesActivity$1$1.onClick(ManageConnectedServicesActivity.java:63)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
创建一个视图来扩充 xml 文件,并在之前使用该视图findViewById()
final View view = inflater.inflate(R.layout.schedule,null);
builder.setView(view);
final EditText edtSelectDate = (EditText) view.findViewById(R.id.edtSelectDate);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)