Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android how to setOnClickListener for fragment button

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?

like image 280
Roy Hinkley Avatar asked Dec 20 '22 15:12

Roy Hinkley


2 Answers

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

like image 146
compuguru Avatar answered Jan 06 '23 08:01

compuguru


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);
    }
like image 42
raging met Avatar answered Jan 06 '23 08:01

raging met