我在findViewById
中使用Fragment
时收到错误消息。
我该如何解决?
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");
}
}
}
答案 0 :(得分:2)
您必须使用根视图才能使用findViewById
:
假设此布局id.bottomNavViewBar
中包含此视图layout.fragment_discover
或包含:
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");
}
}
}
现在,只要您需要使用findViewById
,就可以使用root
视图,如下所示:
root.findViewById(R.id.yourview)