how to set an onclick listener for an imagebutton in an alertdialog

匿名 (未验证) 提交于 2019-12-03 02:50:02

问题:

I have a layout with an ImageButton that is inflated in an AlertDialog, where/how should I set an onClick listener?

Here's the code I tried using:

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

回答1:

Try to put like this in ur code

e.g:-if your alertdialog's object is ad,then

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


回答2:

The code above proved useful but I used "this" (not "ad") for the context:

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

This is easier for copying and pasting ;-)

Thanks for the previous code I woulnd have found the solution above without it.



回答3:

Try to this in your code.

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

Use this method from

  <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="showAlertDialogButtonClicked"/> 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!