如何在Android中使用Dialog OnClick Listner?
我是Android开发新手。如果我的问题很简单,请原谅 我尝试使用XML在Android布局视图上创建一个按钮。现在在Activity类中,我尝试获取按钮并向其添加一个点击列表。这工作正常,没有任何问题 在我前面解释过的按钮点击的类似行中,弹出了一个对话框。在这个对话框中,我有一个ImageButton。单击此图像按钮时,我尝试使用下面的代码设置单击列表如何在Android中使用Dialog OnClick Listner?,android,android-layout,android-lifecycle,Android,Android Layout,Android Lifecycle,我是Android开发新手。如果我的问题很简单,请原谅 我尝试使用XML在Android布局视图上创建一个按钮。现在在Activity类中,我尝试获取按钮并向其添加一个点击列表。这工作正常,没有任何问题 在我前面解释过的按钮点击的类似行中,弹出了一个对话框。在这个对话框中,我有一个ImageButton。单击此图像按钮时,我尝试使用下面的代码设置单击列表 The Activity on create is as below @凌驾 public void onCreate(Bundle sa
The Activity on create is as below
@凌驾
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button button = (Button) findViewById(R.id.btnAdd);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
final Button btnAdd = (Button) findViewById(R.id.btnAdd);
if(v==btnAdd) {
dialog = new Dialog(this);
dialog.setContentView(R.layout.add_dialog);
dialog.setTitle("Test Title.");
dialog.setCancelable(true);
dialog.show();
final ImageButton button = (ImageButton) findViewById(R.id.imageButton1);
try {
Log.i("Log","1");
button.setOnClickListener(this);
Log.i("Log","2");
}
catch(Exception e)
{
Log.i("Log","3");
dialog.dismiss();
//Dialog d = new Dialog(this);
//d.setTitle("test.");
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
Toast.makeText(this,e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
Log.i("Log","4");
//d.show();
Log.i("Log","5");
}
}
}
在上面的步骤中,我按照这个顺序获取日志。1,3,4,5. 我不明白。在toast中,我得到了blank消息,blank后跟java.lang.Nullexception
但当执行时,会弹出一个强制关闭窗口。请告诉我怎么做。或者有没有解决办法?我需要有一个对话框来点击按钮,然后在对话框中我需要有一个以上的按钮选项。对于对话框中的每个按钮,我需要执行不同的活动。任何形式的帮助或建议都是值得赞赏的。提前感谢您的时间和帮助。您很可能正在尝试从
活动中检索按钮。它返回null,因为此方法仅检索附加到活动的资源(通过使用方法setContentView
)
您有两个选择:
- 可以使用
- 如果要扩展Dialog类,请在该类中添加侦听器
更新后编辑:
正如我上面所说,问题是:
final ImageButton button = (ImageButton) findViewById(R.id.imageButton1);
因为imageButton1不是活动中布局的一部分。只需将其替换为:
final ImageButton button = (ImageButton) dialog.findViewById(R.id.imageButton1);
很可能您正试图从活动
类中检索按钮。它返回null,因为此方法仅检索附加到活动的资源(通过使用方法setContentView
)
您有两个选择:
- 可以使用
- 如果要扩展Dialog类,请在该类中添加侦听器
更新后编辑:
正如我上面所说,问题是:
final ImageButton button = (ImageButton) findViewById(R.id.imageButton1);
因为imageButton1不是活动中布局的一部分。只需将其替换为:
final ImageButton button = (ImageButton) dialog.findViewById(R.id.imageButton1);
你有什么例外?请显示logcat输出您是否为对话框使用自定义布局?是的,我为对话框使用自定义布局。错了吗?对话框创建的完整源代码将帮助我们帮助您我已经修改了代码。请看一看,如果你需要更多的细节,请告诉我。谢谢你抽出时间。你有什么例外?请显示logcat输出您是否为对话框使用自定义布局?是的,我为对话框使用自定义布局。错了吗?对话框创建的完整源代码将帮助我们帮助您我已经修改了代码。请看一看,如果你需要更多的细节,请告诉我。谢谢你抽出时间,我也同意。按钮已从活动中检索。感谢您的回复。我会很快尝试一下,并让你知道。谢谢。非常感谢你的代码。它帮助我理解了这个问题。这一变化对我起了作用。:-)我也同意。按钮已从活动中检索。感谢您的回复。我会很快尝试一下,并让你知道。谢谢。非常感谢你的代码。它帮助我理解了这个问题。这一变化对我起了作用。:-)