简体   繁体   English

处理自定义对话框中的按钮

[英]Handling buttons in custom dialogs

I have a little problem with an android custom dialog. 我有一个Android自定义对话框的问题。

I construct a custom dialog in the onCreateDialog(int) function: 我在onCreateDialog(int)函数中构造了一个自定义对话框:

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

I have a onClick(View) function in the same class: 我在同一个类中有一个onClick(View)函数:

   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定义:

<?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?). 但是Button不起作用(应用程序崩溃) - 这很好,因为回调的onClick函数是在我的主要活动中定义的 - 对话框是一个新活动(我是对的吗?)。

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? 很长的路要是继承Dialog并在那里写下所有东西 - 但还有另一种我看不到的方法吗?

The way round it that I use, rather than having a switch block is to use onClickListeners for the buttons: 我使用它的方式,而不是有一个开关块是使用onClickListeners为按钮:

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. 请注意,您正在从对话框中查找视图,而不是直接调用findViewById,因为它将返回空指针,因为应用程序视图上不会有dialog_button。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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