2011-04-28 46 views
13

我有一個在AlertDialog中充氣的ImageButton的佈局,其中/如何設置onClick監聽器?如何爲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(); 
     } 
    }); 
+0

我發現我在做什麼錯了這種方法,我需要先找到充氣視圖的ImageButton。 – Yvonne 2011-04-28 02:48:42

回答

21

嘗試把這樣在我們的代碼

例如: - 如果您的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(); 
     } 
    }); 
+0

謝謝,這與我之前發現的解決方案類似 – Yvonne 2011-04-28 05:23:46

1

代碼上面證明是有用的,但我在上下文中使用了「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(); 
     } 

這是更容易複製和粘貼;-)

感謝您的前代碼我woulnd找到了上述解決方案沒有它。

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