2011-04-28 8 views
13

AlertDialogでImageButtonを拡張したレイアウトがあります。ここでどのようにonClickリスナーを設定する必要がありますか?alertdialogのimagebuttonにonclickリスナーを設定する方法

ここで私が使用してみましたコードです:コードは、あなたのalertdialogのオブジェクトは広告である-ifその後、

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

から、この方法は、私が最初に膨張したビューからのImageButtonを見つける必要がありました。 – Yvonne

答えて

21

は、例えばウルのコードの中でこのよう

を置くようにしてください上記の文脈では「広告」ではなく「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(); 
     } 

コピーと貼り付けが簡単です

私は以前のコードのおかげで、上記の解決策が見つかりませんでした。

+0

ありがとう、それは以前私が見つけた解決策に似ていた – Yvonne

1

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

あなたのコードでこれを試してください。

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"/> 
関連する問題