Using onClick attribute in layout xml causes a NoS

2019-01-06 17:53发布

I have created a custom dialog and a layout xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tap Me"
        android:onClick="dialogClicked" />
</LinearLayout>

In the dialog class I've implemented the method "dialogClicked(View v)":

public class TestDialog extends Dialog {

 public TestDialog(final Context context)
 {
  super(context);
 }

 @Override
 protected void onCreate(final Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog);
 }

 public void dialogClicked(final View view)
 {
  System.out.println("clicked");
 }

}

When I tap the button I get a NoSuchMethodException 'dialogClicked'. Setting the onClick handler in layout xml works fine for activities, but not in dialogs. Any ideas? What I'm doing wrong?

9条回答
2楼-- · 2019-01-06 18:53

Try to define that method (dialogClicked) in the activity and not in the dialog.

It might use reflection so if you use different activities just write that method in each activity that might show that dialog

查看更多
地球回转人心会变
3楼-- · 2019-01-06 18:56

Dialogs need the signature

dialogClicked(DialogInterface dialog, int id) { ... }
查看更多
姐就是有狂的资本
4楼-- · 2019-01-06 18:59

Define the method (dialogClicked) in Activity. And modify TestDialog like the following code:

public class TestDialog extends Dialog {
 Context mContext;
 public TestDialog(final Context context)
 {

  super(context);
  mContext=context;
 }

 @Override
 protected void onCreate(final Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  LinearLayout ll=(LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.dialog, null);
  setContentView(ll); 
 }
}

I think it works :)

查看更多
登录 后发表回答