This is my first try on Fragments and I'm not able to handle android:onClick
I have a button inside my fragment XML like this
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/save_keywords_button"
android:id="@+id/save_keywords"
android:layout_marginTop="340dp"
android:background="#FF2E7D32"
android:textColor="#FFFFFF"
android:typeface="normal"
android:onClick="myLogic" />
I searched many results and can't get the exact solution to handle the onClick event.
My question is, How can I get the ID of my button and write the myLogic method. FindViewById() is not working in fragments and where should I write the method? in fragment or in my activity?
Better approach would be implementing OnClickListener
to your fragment class and overriding onCreateView
in your fragment where you assign the listener to your button.
By putting onClick
attribute in your XML layout, your activity on load will look for the element in the activity, not in the fragment. This will throw exception.
I would suggest reading some fragment-activity hierarchy to understand when is it possible to access elements in your fragment.
public class StartFragment extends Fragment implements OnClickListener{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_start, container, false);
Button b = (Button) v.findViewById(R.id.save_keywords);
b.setOnClickListener(this);
return v;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.save_keywords:
...
break;
}
}
}
Reference from: here
android:onClick="myLogic"
will not call the method myLogic
inside the fragment. Use OnClickListener
instead to handle this type of events.
See these below references
Best way to implement View.OnClickListener in android
http://developer.android.com/reference/android/view/View.OnClickListener.html
If you need to get view in fragmen you can do this getView().findViewById(R.id.foo);
only after onCreateView()
has been called. And if you specify onClick
in xml, you do not need to code any linking to that method in your program, just implement that method in your activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With