2011-04-28 32 views
13

Tôi có một bố trí với một ImageButton được thổi phồng trong một AlertDialog, nơi/làm thế nào tôi nên thiết lập một người nghe onClick?làm thế nào để thiết lập một người nghe onclick cho một imagebutton trong một alertdialog

Dưới đây là đoạn code tôi đã cố gắng sử dụng:

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

tôi thấy những gì tôi đang làm sai, tôi cần thiết để tìm ra ImageButton từ cái nhìn đầu tiên thổi phồng. – Yvonne

Trả lời

21

Cố gắng đặt như thế này trong mã ur

ví dụ: -Nếu đối tượng của alertdialog của bạn là quảng cáo, sau đó

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

cảm ơn, điều đó tương tự như giải pháp tôi đã tìm thấy trước đó – Yvonne

1

Mã ở trên tỏ ra hữu ích nhưng tôi đã sử dụng "điều này" (không phải "quảng cáo") cho ngữ cảnh:

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

Việc sao chép và dán này dễ dàng hơn ;-)

Cảm ơn mã trước tôi đã tìm ra giải pháp ở trên mà không có nó.

0

Hãy thử điều này trong mã của bạn.

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

Sử dụng phương pháp này từ

<Button android:layout_width="match_parent" 
android:layout_height="wrap_content" android:onClick="showAlertDialogButtonClicked"/> 
Các vấn đề liên quan