Как установить прослушиватель onclick для кнопки изображения в alertdialog
У меня есть макет с ImageButton, который накачивается в AlertDialog, где/как я должен установить прослушиватель 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();
}
});
Ответы
Ответ 1
Попробуйте сделать это в коде ur
например: -если ваш объект 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();
}
});
Ответ 2
Вышеприведенный код оказался полезным, но я использовал "this" (не "объявление" ) для контекста:
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();
}
Это проще для копирования и вставки; -)
Спасибо за предыдущий код, который я нашел без него.
Ответ 3
Попробуйте это в своем коде.
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"/>