Android 如何在alertdialog中为imagebutton设置onclick侦听器

Android 如何在alertdialog中为imagebutton设置onclick侦听器,android,onclick,android-alertdialog,imagebutton,Android,Onclick,Android Alertdialog,Imagebutton,我有一个在AlertDialog中膨胀的带有ImageButton的布局,我应该在哪里/如何设置onClick侦听器 以下是我尝试使用的代码: ImageButton ib = (ImageButton) findViewById(R.id.searchbutton); ib.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {

我有一个在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();
        }
    });

试着在你的代码中这样写

e、 g:-如果alertdialog的对象是ad,则

 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();
        }
    });

上面的代码证明很有用,但我在上下文中使用了“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();
        }
这便于复制和粘贴;-)


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

请尝试在代码中使用此选项。

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"/>

我发现我做错了什么,我需要首先从充气视图中找到ImageButton。