0

I get an error when I use findViewById in Fragment.

How can I solve it?

public class Discover extends Fragment {

private static final String TAG = "Discover";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_discover, container, false);
    Log.d(TAG, "onCreate: starting.");
    setupBottomNavigationView();
    return root;
}

private void setupBottomNavigationView(){

    Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
    BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
    BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);

}

public void onResume(){
    super.onResume();

    // Set title bar
    ((LandingPage) getActivity())
            .setActionBarTitle("Discover Photos");

   }

  }
}
Pau
  • 14,917
  • 14
  • 67
  • 94

1 Answers1

2

You have to use the root view for using findViewById:

Assuming this view id.bottomNavViewBar exist in this layout layout.fragment_discoveror included:

public class Discover extends Fragment {
View root;

private static final String TAG = "Discover";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
// Inflate the layout for this fragment
root = inflater.inflate(R.layout.fragment_discover, container, false);
Log.d(TAG, "onCreate: starting.");
setupBottomNavigationView();
return root;
}

private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) root.findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);

}

public void onResume(){
super.onResume();

// Set title bar
((LandingPage) getActivity())
        .setActionBarTitle("Discover Photos");

    }

  }
}

Now whenever you need to use findViewById, you can use the root view like this:

root.findViewById(R.id.yourview)
S.R
  • 2,819
  • 2
  • 22
  • 49