Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Handle onClick in Fragments [duplicate]

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?

like image 334
Uday Avatar asked Feb 21 '16 08:02

Uday


3 Answers

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

like image 146
parohy Avatar answered Oct 03 '22 20:10

parohy


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

like image 21
GeekDroid Avatar answered Oct 03 '22 19:10

GeekDroid


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.

like image 42
callOfCode Avatar answered Oct 03 '22 18:10

callOfCode