How to handle onClick in fragments

This is my first attempt at Fragments, and I cannot process android: onClick

I have a button inside my XML fragment like

    <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 a lot of results and cannot get the exact solution to handle the onClick event.

My question is: how can I get the identifier of my button and write myLogic method. FindViewById () does not work in fragments and where should the method be written? in a fragment or in my activity?

+4
source share
4 answers

An improved approach will be implemented OnClickListenerfor your fragment class and redefined onCreateViewin your fragment, where you assign a button to the listener.

onClick XML-, , . .

, , .

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;
    }
}
}

:

+9

public void myLogic(View v)
+1

If you need to get an idea in fragmen, you can getView().findViewById(R.id.foo);only do this after it has been called onCreateView(). And if you specify onClickin xml, you do not need to specify any link to this method in your program, just implement this method in your activity.

+1
source

Source: https://habr.com/ru/post/1629755/


All Articles