首页 > 解决方案 > 片段中的回收站视图

问题描述

我试图在我的片段中实现回收器视图,但这些错误并没有让我这样做,请查看并告诉我

这是我的片段java类

public class HomeFragment extends Fragment {

private HomeViewModel homeViewModel;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel.class);
    View root = inflater.inflate(R.layout.fragment_home, container, false);

    MyListData[] myListData = new MyListData[] {
            new MyListData("Email", android.R.drawable.ic_dialog_email),
            new MyListData("Info", android.R.drawable.ic_dialog_info),
            new MyListData("Delete", android.R.drawable.ic_delete),
            new MyListData("Dialer", android.R.drawable.ic_dialog_dialer),
            new MyListData("Alert", android.R.drawable.ic_dialog_alert),
            new MyListData("Map", android.R.drawable.ic_dialog_map),
            new MyListData("Email", android.R.drawable.ic_dialog_email),
            new MyListData("Info", android.R.drawable.ic_dialog_info),
            new MyListData("Delete", android.R.drawable.ic_delete),
            new MyListData("Dialer", android.R.drawable.ic_dialog_dialer),
            new MyListData("Alert", android.R.drawable.ic_dialog_alert),
            new MyListData("Map", android.R.drawable.ic_dialog_map),
    };
    RecyclerView recyclerView = root.findViewById(R.id.recyclerView);
    MyListAdapter adapter = new MyListAdapter(myListData);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);
    return root;
   }
}

我在这些行上出错 RecyclerView recyclerView = root.findViewById(R.id.recyclerView) 和 recyclerView.setLayoutManager(new LinearLayoutManager(this));

这是我的片段视图模型类

public class HomeViewModel extends ViewModel {

  private MutableLiveData<String> mText;

  public HomeViewModel() {
      mText = new MutableLiveData<>();
      //mText.setValue();
  }

  public LiveData<String> getText() {
      return mText;
   }
}

这是我的xml

<androidx.recyclerview.widget.RecyclerView
                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"
                android:layout_below="@id/t1"
                android:scrollbars="vertical"
                android:id="@+id/recyclerView"
                />

标签: androidandroid-studioandroid-layoutandroid-fragmentsandroid-livedata

解决方案


尝试这个,

RecyclerView recyclerView = root.findViewById(R.id.recyclerView); 
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
Rcv_Results.setLayoutManager(mLayoutManager);

推荐阅读