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?
Try changing where you set the listener to the
onActivityCreatedinstead ofonAttach. According to the Android docs:When you call
onAttachthat’s before the Activity has setup its view