尝试使用findViewById时片段中的错误

时间:2017-06-05 00:03:31

标签: android android-fragments fragment findviewbyid bottomnavigationview

我在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");

   }

  }
}

1 个答案:

答案 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)