我是Android开发的新手。如果我的问题很简单,请原谅。
我尝试使用XML在我的Android布局视图上创建一个按钮。现在,在Activity类中,我正在尝试获取按钮并添加一个点击列表。这很好,没有任何问题。
在按钮点击的类似行上,我之前解释过,我弹出了一个对话框。在这个对话框中,我有一个ImageButton。点击此图像按钮时,我正试图使用以下代码设置一个点击列表。
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。我不明白2。在toast中,我得到的消息是blank,blank后面跟着java.lang.Nullexception.
但这个在执行时会弹出一个强制关闭的弹出窗口。请建议如何做到这一点。或者有什么解决办法吗?我需要有一个对话框来点击按钮,然后在对话框中我需要有多个按钮选项。对于对话框中的每个按钮,我需要执行不同的活动。任何形式的帮助或建议都是可观的。提前感谢您的时间和帮助。
很可能您正试图从Activity
类中检索按钮。它返回null,因为此方法将仅检索附加到"活动"的资源(通过使用方法setContentView
)。
你有两个选择:
- 可以使用layout充气器对对话框布局进行充气
- 如果要扩展Dialog类,请改为在该类中添加侦听器
更新后编辑:
正如我上面所说,问题是:
final ImageButton button = (ImageButton) findViewById(R.id.imageButton1);
因为imageButton1不是活动中布局的一部分。只需将其替换为:
final ImageButton button = (ImageButton) dialog.findViewById(R.id.imageButton1);