foobar5512
foobar5512

Reputation: 2490

ImageButton is Null

I have an ImageButton in a fragment that is opened by a TabLayout in my main activity. When I try to get a reference to the ImageButton in my main activity inside onCreate(Bundle savedInstance):

 playPauseButton = (ImageButton)findViewById(R.id.play_pause);

it returns as null. The fragment that encloses my ImageButton looks like this:

 <ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/play_pause"
    android:layout_gravity="center_horizontal"
    />

Any ideas on why this returns null?

Upvotes: 0

Views: 356

Answers (3)

Sathish Kumar J
Sathish Kumar J

Reputation: 4335

If you extends Fragment means should use like,

@Override

public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.YOUR_LAYOUT_FILE_NAME, container, false);
    ImageButton playPauseButton = (ImageButton)rootView.findViewById(R.id.play_pause);


    return view;

}

This may helps you

Upvotes: 0

Sohail Zahid
Sohail Zahid

Reputation: 8149

get reference like this by using getView()

 playPauseButton = (ImageButton) getView().findViewById(R.id.play_pause);

Upvotes: 1

Muhammed Refaat
Muhammed Refaat

Reputation: 9103

You can't get the view inside a fragment from the MainActivity directly like this as its not a view included in it, it included in the fragment, so you have to get it from within the fragment itself after it has been created(i.e in the onViewCreated() method) and with the instance of the view created for the fragment:

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

     // Declaring the View you want
     ImageButton play_pause = (ImageButton) view.findViewById(R.id.play_pause);

 }

Upvotes: 2

Related Questions