I'm trying to invoke the method in my onClick (View v) XML, but does not work with Fragment. This is the error.
01-17 12:38:36.840: E/AndroidRuntime(4171): java.lang.IllegalStateException:
Could not find a method insertIntoDb(View) in the activity class main.MainActivity
for onClick handler on view class android.widget.Button with id 'btn_conferma'
MainActivity.java
public void insertIntoDb(View v) {
...
}
xml code
<Button
android:id="@id/btn_conferma"
style="?android:attr/borderlessButtonStyle"
android:layout_width="0.0dip"
android:layout_height="45dp"
android:layout_marginLeft="2dp"
android:layout_weight="1.0"
android:background="@drawable/bottoni"
android:gravity="center_horizontal|center_vertical"
android:onClick="insertIntoDb"
android:text="SALVA"
android:textColor="#ffffff"
android:textSize="16sp" />
Another option may be to have your fragment implement View.OnClickListener and override onClick(View v) within your fragment. If you need to have your fragment talk to the activity simply add an interface with desired method(s) and have the activity implement the interface and override its method(s).
http://developer.android.com/training/basics/firstapp/starting-activity.html http://developer.android.com/training/basics/fragments/communicating.html
This is not an issue, this is a design of Android. See here:
A possible workaround would be to do something like this in your MainActivity:
and then in your Fragment class:
You OK !!!!
The others have already said that methods in onClick are searched in activities, not fragments. Nevertheless, if you really want it, it is possible.
Basically, each view has a tag (probably null). We set the root view's tag to the fragment that inflated that view. Then, it is easy to search the view parents and retrieve the fragment containing the clicked button. Now, we find out the method name and use reflection to call the same method from the retrieved fragment. Easy!
in a class that extends
Fragment
:all activities are derived from the same ButtonHandlingActivity:
ButtonHandlingActivity.java:
It has to define methods for all xml onClick handlers.
com/example/customandroid/OnClickFragments.java:
And the next adventure will be proguard obfuscation...
PS
It is of course up to you to design your application so that the data live in the Model rather than in Activities or Fragments (which are Controllers from the MVC, Model-View-Controller point of view). The View is what you define via xml, plus the custom view classes (if you define them, most people just reuse what already is). A rule of thumb: if some data definitely must survive the screen turn, they belong to Model.
Your activity must have
not Fragment .
If you don't want the above in activity. initialize button in fragment and set listener to the same.
Then