我想使用Tab / Fragment显示RecyclerView,但是我不知道该怎么做,因为Fragment类的方法返回一个View,而不是Reclycler View:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.fragment_needs, container, false);
return myFragmentView;
}
fragment.xml的代码是:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NeedsFragment">
<FrameLayout
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp">
<android.support.v7.widget.RecyclerView
android:id="@+id/all_user_need_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</FrameLayout>
</RelativeLayout>
谢谢。
答案 0 :(得分:0)
首先,您的onCreateView()
方法没有意义:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.fragment_needs, container, false);
return needsFragmentRecyclerView; //you should be returning myFragmentView here, not whatever needsFragmentRecyclerView is
}
第二,增加布局后,只需使用findViewById()
:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.fragment_needs, container, false);
RecyclerView recyclerView = myFragmentView.findViewById(R.id.all_user_need_list); //assign to a global variable if needed
return myFragmentView; //replaced with the proper variable
}
或者,您可以从Fragment中的任何位置获取RecyclerView,只要它在以下位置称为 onCreateView()
,即可:
RecyclerView recyclerView = getView().findViewById(R.id.all_user_need_list);
答案 1 :(得分:0)
您可以在onCreateView()方法中返回从android.view类继承的任何类型的视图组件和自定义视图。