0

这是我的 dialog_date_range.xml 对话框布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:foo="http://schemas.android.com/apk/res/com.example.database_fragment"
    android:id="@+id/dialog_body"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:onClick="toggleDateRange"
        android:text="Button" />
</LinearLayout>

在我的活动中,我有:

public void toggleDateRange(View v) {
    if(dialog == null) {
        dialog = new Dialog(context, R.style.PauseDialogAnimation);
        dialog.setCancelable(true);
        dialog.setContentView(R.layout.dialog_date_range);
        dialog.getWindow().getAttributes().windowAnimations = R.style.PauseDialogAnimation;
    }

    if(dialog.isShowing()) {
        dialog.dismiss();
    } else {
        dialog.show();
    }
}

这是我单击按钮时遇到的错误:

FATAL EXCEPTION: main E/AndroidRuntime(25357): java.lang.IllegalStateException:   
Could not find a method toggleDateRange(View) in the activity class   
android.view.ContextThemeWrapper for onClick handler on view class   
android.widget.Button    
 with id 'button1'at android.view.View$1.onClick(View.java:3586) 
4

2 回答 2

2

KISS - 保持简单愚蠢(对不起最后一句话:P)

<Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:text="Button" />

实现 onClickListener

        Button btn1 = (Button)findViewById(R.id.button1);
        btn1.setonClickListener(this);

//实现的方法

    @Override
    public void onClick(View v) {

      switch(v.getId){

         case R.id.button1:{

         //do here whatever you want
  }
 }
}

或者,如果您真的想这样做, setContentView 中的 VIEW 不是正确的。我创建了一个新项目并添加了与您完全相同的代码,并且它可以工作。检查您是否在设置按钮的视图中。

于 2013-07-26T14:37:17.020 回答
0

根据此答案,Android 在对话框中找不到活动的方法。所以解决方案是只为按钮设置onClickListener: java.lang.illegalstateexception在活动类android片段中找不到方法(视图)

将您的代码更改为如下所示:

public void toggleDateRange(View v)
{
    if (dialog == null)
    {
        dialog = new Dialog(this, R.style.AppBaseTheme);
        dialog.findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v)
            {
                toggleDateRange(v);

            }
        });
        dialog.setCancelable(true);
        dialog.setContentView(R.layout.dialog_date_range);
        dialog.getWindow().getAttributes().windowAnimations = R.style.AppBaseTheme;
    }

    if (dialog.isShowing())
    {
        dialog.dismiss();
    }
    else
    {
        dialog.show();
    }
}
于 2013-07-26T15:14:26.123 回答