【问题标题】:I need to inflate a RecyclerView inside a Fragment AndroidStudio我需要在 Fragment Android Studio 中充气 RecyclerView
【发布时间】:2018-10-09 22:16:22
【问题描述】:

我想使用 Tab/Fragment 来显示 RecyclerView,但我不知道该怎么做,因为 Fragment 类的方法返回的是 View,而不是 Reclyler 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>

谢谢你。

【问题讨论】:

    标签: android listview android-recyclerview tabs fragment


    【解决方案1】:

    首先,您的 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);
    

    【讨论】:

      【解决方案2】:

      您可以在 onCreateView() 方法中返回任何类型的视图组件和继承自 android.view 类的自定义视图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多