【问题标题】:Button onClick inside view used in Alert Dialog按钮 onClick 在警报对话框中使用的内部视图
【发布时间】:2013-07-05 16:12:34
【问题描述】:

我在布局文件中有一个按钮,用于创建自定义警报对话框。由于不相关的原因,我需要使用布局内的按钮,而不是使用对话框内置按钮。

它实际上与这个问题非常相似:

Android:Button in AlertDialog

问题是,当我点击警报对话框中的按钮时,似乎永远不会调用 onClick。

这是我活动中 OnCreate 中代码的相关部分:

LayoutInflater dcvI = LayoutInflater.from(this);
final View dcv = dcvI.inflate(R.layout.dialog,null);
final Button sd_abort = (Button)dcv.findViewById(R.id.abort1);
sd_abort.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {

//I do work here

}});

警报对话框代码:

View exp =  LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog,null,false);

new AlertDialog.Builder(MainActivity.this, R.style.CustomDialogTheme)
.setTitle("Warning!!!")
.setIcon(R.drawable.dhd_icon)
.setView(exp)
.show();

有人知道我是否遗漏了使按钮和 onclick 侦听器无法连接的东西吗?

谢谢

【问题讨论】:

  • 这两个按钮似乎根本没有连接。
  • 你能解释一下吗?我在侦听器“abort1”中的按钮位于我用作警报对话框的基础的 layout/xml/view 中。该按钮显示在对话框中。我想我的问题是,如果我做得不对,我怎么能听到警报对话框中的按钮?

标签: android android-view android-alertdialog onclicklistener


【解决方案1】:

你可以新建一个按钮监听类

public class ButtonListener implements OnClickListener {

    @Override
    public void onClick(View v) {
        // do your work

    }

}

然后在你的两个按钮上设置它们

ButtonListener buttonListener = new ButtonListener();
sd_abort.setOnClickListener(buttonListener);

(在您的对话框中)

View exp =  LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog,null,false);

Button dialogButton = (Button)exp.findViewById(R.id.abort1);
dialogButton.setOnClickListener(buttonListener);
new AlertDialog.Builder(MainActivity.this, R.style.CustomDialogTheme)
.setTitle("Warning!!!")
.setIcon(R.drawable.dhd_icon)
.setView(exp)
.show();

【讨论】:

  • 这似乎奏效了。我不知道为什么会这样,但确实如此。因此,感谢您的所有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
相关资源
最近更新 更多