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?
Following on from Jett Hsieh's post, I've implemented my dialogs slightly differently using showDialog and dismissDialog, but the fundamentals of getting the android:onClick working have been the same, my example code is below for future reference.
And the layout file:
I think the issue is one of scope. I'm not sure how'd you address this in xml, but essentially the dialogueClicked method in your layout xml doesn't know where to find the method you've defined in the dialog class.
The standard approach i've seen to bind buttons in custom layouts is as follows.
.
}
Hope that helps. Would still be interested in knowing if there was a solution to using xml onClick to bind to the method. Perhaps an additional argument in the setContentView? something r'other.
system looks for the method in the where the layout has been inflated from, or in the activity class to which the xml was set as content.
A dialog is always created and displayed as part of an Activity. According to Android References:
Also, are you passing the object returned by getApplicationContext(); to the constructor of TestDialog?
android:onClick="method"
is pretty cool, but it doesn't work on Android 1.5 so I am avoiding for some time.An easy workaround:
Make your
Dialog
anActivity
and useandroid:theme="@android:style/Theme.Dialog"
in youAndroidManifest
.I've found the following code in the View.java source:
-> The views uses its context to resolve the onclick handler method.
Noew the following code from Dialog.java source:
In the constructor of the dialog an instance of ContextThemeWrapper gets created and set as context. This instance is neither the custom dialog class, nor the calling activity, which can be the place for implementing the handler method. Therefore views are not able to find the onclick handler method.
But I have to use the onclick XML attribut. Any workarounds available?