Fragment implements OnClickListener

Nick picture Nick · Aug 8, 2012 · Viewed 59.6k times · Source

I've got an application that I'm modernizing. One step of this process is changing to a Fragment based layout (using the Fragments from the support library). I converted my Activities into Fragments, and got the layout working nicely (using a ViewPager, cool stuff!)

I was having my Activities implement OnClickListener for all of my button-pressing needs. I have the new Fragment incarnations doing the same thing of course, but it looks like "onClick" is never getting hit. Is there something special about Fragments that prevents them from working this way?

Answer

Abhijit Chakra picture Abhijit Chakra · Feb 19, 2013

Just do one this

public class fragmentOne extends Fragment implements OnClickListener {
    Button myButton;

    @Override
    public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState) {
        View myView = inflater.inflate(R.layout.fragment_1, container, false);
        myButton = (Button) myView.findViewById(R.id.myButton);
        myButton.setOnClickListener(this);
        return myView;
    }

    @Override
    public void onClick(View v) {
        // implements your things
    }
}

very simple