Android &引用;找不到id“的视图”;使用RecyclerView时
我正在用RecyclerViews尝试我的第一步。我走得很远,我了解一切。但是,我在尝试运行代码时遇到“找不到id的视图…”错误 这是DictionaryFragment的onCreateView方法:Android &引用;找不到id“的视图”;使用RecyclerView时,android,android-fragments,android-recyclerview,Android,Android Fragments,Android Recyclerview,我正在用RecyclerViews尝试我的第一步。我走得很远,我了解一切。但是,我在尝试运行代码时遇到“找不到id的视图…”错误 这是DictionaryFragment的onCreateView方法: public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView =
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dictionary_list, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.dictionaryList);
adapter = new DictionaryAdapter(getActivity(), getDictionaryData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return rootView;
}
dictionary_list.xml如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/grey"
android:paddingBottom="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="@drawable/rounded_corners"
android:orientation="vertical"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/dictionaryList"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
您需要在onViewCreated方法中设置RecyclerView
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = (RecyclerView) rootView.findViewById(R.id.dictionaryList);
adapter = new DictionaryAdapter(getActivity(), getDictionaryData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
并在onCreateView中膨胀视图
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.dictionary_list, container, false);
}
这种行为的原因是充气器.inflate only实际上并不会充气视图以避免阻塞ui线程,并且在以后异步运行。完成充气后,调用ViewCreated。在onCreateView buzt中创建视图或调用充气机通常是不好的做法。谢谢,@JarodCoding,但这没有帮助。实际上,android开发者页面上的示例与我在onCreateView中膨胀recycler视图的方式相同:[链接]
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.dictionary_list, container, false);
}