0

我是 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 中,我收到空白消息,空白后跟 java.lang.Nullexception。

但这在执行时会给我一个强制关闭弹出窗口。请建议如何做到这一点。或者有没有相同的解决方法?我需要有一个对话框来单击按钮,然后在对话框中我需要有多个按钮选项。对于对话框中的每个按钮,我需要执行不同的活动。任何形式的帮助或建议都是可观的。提前感谢您的时间和帮助。

4

1 回答 1

3

很可能您正在尝试从Activity类中检索按钮。它返回 null 因为此方法将仅检索附加到 Activity 的资源(通过使用方法setContentView)。

你有两个选择:

更新后编辑:

正如我上面所说,问题是:

   final ImageButton button = (ImageButton) findViewById(R.id.imageButton1);

因为 imageButton1 不是活动布局的一部分。只需将其替换为:

   final ImageButton button = (ImageButton) dialog.findViewById(R.id.imageButton1);
于 2011-06-03T04:08:30.313 回答