1

私はアンドロイド開発の初心者です。layout.xml で android:onClick を使用して、カスタム ダイアログにあるボタンのイベント ハンドラーを設定しようとしています。しかし、アプリケーションをデバッグすると、カスタム ダイアログのボタンをクリックすると、ソース コードが見つからないと言われました。しかし、レイアウト ファイルで属性の代わりにイベント リスナーを使用すると、うまく機能します。

ここにコードの一部があります

button1 以下を含むメイン アクティビティは、そのボタンのイベント ハンドラです。

public void onClickButton1(View v)
    {
        MyCustomDialog a = new MyCustomDialog(this);        
        a.show();       
    }

ここに MyCustomDialog クラス、別の Java ファイルがあります

public class MyCustomDialog extends Dialog {

    Context m_context;
    public MyCustomDialog (Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        this.m_context = context;       
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        this.setTitle("Custom Dialog");
        this.setContentView(R.layout.custom_dialog);
    }



    public void onClickButtonInDialog(View v)
    {
        AlertDialog a = new AlertDialog.Builder(this.m_context).create();
        a.setTitle("Ok");
        a.show();
    }
}

最後はカスタム ダイアログ レイアウト ファイルです。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button_in_dialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:onClick="onClickButtonInDialog"
        android:text="Add" />

</RelativeLayout>
4

2 に答える 2

2

不可能です。次のようなコールバックを登録する必要があります。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setTitle("Custom Dialog");
    View v = LayoutInflater.from(getContext()).inflate(R.layout.custom_dialog);
    this.setContentView(v);
    v.findViewById(R.id.button_in_dialog).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            onClickButtonInDialog(v);
        }
    });
}
于 2012-12-07T18:29:17.200 に答える
0

ここでわかるように、それは可能です。ただし、ビューを設定したのと同じアクティビティのコンテキストに onClick ハンドラーを配置する必要があります。ダイアログのコンテキストから onClick を使用できるかどうかについては、詳細に (またはまったく) 言及していません。 . リスナーをアクティビティに配置し、既存のダイアログを作成するだけです。そうすれば、リスナーが登録され、カスタム ダイアログが引き続き表示されます。

于 2012-12-07T19:18:34.810 に答える