简体   繁体   中英

Handling buttons in custom dialogs

I have a little problem with an android custom dialog.

I construct a custom dialog in the onCreateDialog(int) function:

dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");

I have a onClick(View) function in the same class:

   public void onClick(View v) {
        switch(v.getId()) {
        case R.id.dialog_button:
            Log.i("pma57","dialog button pressed");
            break;
        case R.id.main_button:
            showDialog(DIALOG_CUSTOM);
            break;
        }       
    }

This is the XML definition:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:paddingLeft="20dp"
  android:paddingRight="20dp"
  android:paddingBottom="20dp">
      <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/enter_username" />
      <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
      <Button
        android:id="@+id/dialog_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="OK"
        android:onClick="onClick" />

</LinearLayout>

The Dialog shows up. But the Button does not work (the app crashs)- which is quite ok because the onClick-function for the callback is defined in my main activity - and the dialog is a new activity (am I right?).

But I realy don't know how i implement a button in the dialog - I think this is a fundamental understanding problem of the technic. The long way would be to subclass Dialog and write everything there - but is there another way which I don't see?

The way round it that I use, rather than having a switch block is to use onClickListeners for the buttons:

dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");


Button dialog_btn = (Button) dialog.findViewById(R.id.dialog_button);
dialog_btn.setOnClickListener(new View.OnClickListener() 
{
    // Perform button logic
}

Note that you are finding the view from the dialog, not just calling straight to findViewById as that would return a null pointer as there would be not dialog_button on the application view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM