0

当我在Fragment中使用findViewById时出现错误。片段中的错误,同时尝试使用findViewById

我该如何解决?

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

添加视图在参数

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

} 

或把你的浏览根onCreateView上述

View root; 

    @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(root); 

     return root; 

} 
+0

在视图根(它强调了托架)on setupBottomNavigationView(); –

+0

只需将其添加到setupBottomNavigationView(root); –

+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视图这样的:上述onCreateView它带来的误差

root.findViewById(R.id.yourview) 
+0

非常感谢。这很有帮助 –

+0

很高兴我能提供帮助,如果能解决您的问题,请不要忘记接受其中一个答案。 –