How to Handle onClick in Fragments [duplicate] How to Handle onClick in Fragments [duplicate] xml xml

How to Handle onClick in Fragments [duplicate]


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{@Overridepublic 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;}@Overridepublic 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.