如何为alertdialog中的图像按钮设置onclick监听器

时间:2011-04-28 01:54:44

标签: android onclick alertdialog imagebutton

我有一个带有在AlertDialog中膨胀的ImageButton的布局,我应该在哪里/如何设置onClick监听器?

这是我尝试使用的代码:

    ImageButton ib = (ImageButton) findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }
    });

3 个答案:

答案 0 :(得分:24)

尝试在您的代码中添加这样的内容

例如: - 如果您的alertdialog对象是广告,那么

 ImageButton ib = (ImageButton) ad.findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }
    });

答案 1 :(得分:2)

上面的代码证明很有用,但我在上下文中使用了“this”(而不是“ad”):

    ImageButton ib = (ImageButton) this.findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }

复制和粘贴更容易; - )

感谢前面的代码,我没有找到上面的解决方案。

答案 2 :(得分:0)

在您的代码中尝试此操作。

public void showAlertDialogButtonClicked(View view) {

    // create an alert builder
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Name");

    // set the custom layout
    final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
    builder.setView(customLayout);

    // add a button
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // send data from the AlertDialog to the Activity
            EditText editText = customLayout.findViewById(R.id.editText);
            sendDialogDataToActivity(editText.getText().toString());
        }
    });

    // create and show the alert dialog
    AlertDialog dialog = builder.create();
    dialog.show();
}

使用此方法
  <Button android:layout_width="match_parent"
android:layout_height="wrap_content" android:onClick="showAlertDialogButtonClicked"/>