2011-04-28 47 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"/>