在处理自定义对话框按钮自定义、对话框、按钮

2023-09-13 02:06:54 作者:情场扛把子

我有一个小问题,一个Android自定义对话框。

I have a little problem with an android custom dialog.

我在onCreateDialog(INT)函数构造一个自定义对话框:

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

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

我在同一类的onClick(视图)功能:

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;
        }       
    }

这是XML定义:

<?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>

对话框显示出来。但按钮不起作用(应用程序crashs) - 这是相当好的,因为onClick的函数回调的定义在我的主要活动 - 和对话是一个新的活动(?我是正确的)

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?

推荐答案

的捷径可走的,我使用,而不是一个开关组是使用onClickListeners的按钮:

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
}

请注意,您是从对话框中找到的观点,而不仅仅是打电话直findViewById因为这将返回一个空指针,因为将在应用程序视图中不dialog_button。

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.