Android Fragment Layout Listeners

252 Views Asked by At

I have code that inflates particular fragments based on user choices. I want to set an onCliclListener to a button in a particular fragment layout but I don't know which java file to do so in. I assume it's the fragment java file but I can't initialize the button. Here is what my code currently looks like, could someone help me understand how to code a listener into this?

    public class BlackWidowFragment extends Fragment {


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.blackwidow_fragment, container, false);

        Button btn = (Button) view.findViewById(R.id.playagain_button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BlackWidowFragment.this, Question1.class);
                startActivity(intent);
            }
        });
        return view;
    }
}
1

There are 1 best solutions below

1
On BEST ANSWER

Something like...

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.blackwidow_fragment, container, false);

        Button b = (Button)view.findViewById(R.id.your_button_id);
        b.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                 // do something when clicked...
              }
        });

        return view;
    }