本文介绍了片段中的视图绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 ViewBinding 来处理 Fragment 中的视图.
I want to use ViewBinding to work with Views in Fragment.
FragmentBlankBinding binding;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentBlankBinding.inflate(inflater, container, false);
return binding.getRoot();
}
但是当我尝试从这样的绑定中获取 RecyclerView 时:
But when I try to get RecyclerView from that binding like this:
binding.notesRecyclerView.setAdapter(adapter);
我收到 NullPointerException:
I get NullPointerException:
java.lang.NullPointerException:尝试从字段读取'androidx.recyclerview.widget.RecyclerViewcom.myapps.notes.databinding.FragmentBlankBinding.notesRecyclerView'在空对象引用上
附言这是 fragment_blank.xml:
P.S. here's fragment_blank.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".BlankFragment">
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="@+id/newNoteActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_margin="3dp"
android:elevation="10dp"
app:fab_icon="@drawable/ic_baseline_add_24" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/notesRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</RelativeLayout>
推荐答案
这对我来说很好用:
private FragmentJavaPracticeBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentJavaPracticeBinding.inflate(inflater,container,false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
binding.notesRecyclerView.setVisibility(View.VISIBLE);//this hide/show recyclerview visibility
Log.d("TAG", "hidden: ");
}
这篇关于片段中的视图绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!