android how to setOnClickListener for fragment button

10,879

Solution 1

Try changing where you set the listener to the onActivityCreated instead of onAttach. According to the Android docs:

onActivityCreated is called when the fragment's activity has been created and this fragment's view hierarchy instantiated.

When you call onAttach that's before the Activity has setup its view

Solution 2

Hi im new to android and was getting that nullpointer exception when I added some buttons dynamically. Fragment also has a method onViewCreated you can override. Guessing from its name you can be sure the view is there :)

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    super.onViewCreated(view, savedInstanceState);
    }
Share:
10,879
Roy Hinkley
Author by

Roy Hinkley

Updated on June 04, 2022

Comments

  • Roy Hinkley
    Roy Hinkley almost 2 years

    I have an activity and a fragment. The fragment has a button on it.

    I load the fragment:

    fragment = new FragmentPIN(this);                   
    fragmentTransaction.add(R.id.content,fragment);         
    fragmentTransaction.commit();
    

    then try to set the listener

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
    
            Button cmdOK_PIN = (Button)activity.findViewById(R.id.cmdOK_PIN);
            cmdOK_PIN.setOnClickListener(new View.OnClickListener() {                       
                @Override
                public void onClick(View v) {
    
                }
    
            });
    
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
    }
    

    But I always get a null pointer exception on the setOnClickListener call. The fragment transaction is committed before I attempt to set the listener. Or I think it is. Should I be using another override to do this?