问题描述
我是Kotlin的新手,我尝试创建“购物清单”应用,但片段中的RecycleView遇到问题。
在片段中,我有一个按钮,用户单击该按钮并将Item
添加到列表中,但是当我尝试在OnCreateView
函数中添加布局管理器时出现错误。
我尝试过:
override fun onCreateView(
inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_shopping_list,container,false)
rv_shoppinglist.layoutManager = linearlayoutmanager(context) \\ this is where i get ERR
return view
}
我得到一个错误-> java.lang.IllegalStateException: rv_shoppinglist must not be null
所以我添加了这一行rv_shoppinglist.layoutManager = linearlayoutmanager(context)
在不同的功能上
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
rv_shoppinglist.layoutManager = linearlayoutmanager(activity)
}
现在该应用程序可以正常工作了,当我用户将项目添加到列表中时,它的确会在RecycleView上显示这些项目,但不是在行下划线显示它们,而是在屏幕尺寸上显示它们
图片:
编辑: 这是RV_CHILD的XML文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_item_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
这是shopping_fragment的XML文件
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".fragments.shopping_list">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_shoppinglist"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab_shoppiglist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:src="@drawable/ic_plus"
android:layout_margin="16dp" />
</RelativeLayout>
</FrameLayout>
解决方法
正如评论者所指出的,您的视口布局高度(在您的情况下为RV_CHILD)似乎设置为match_parent
您需要将相对布局高度设置为wrap_content
,否则它将占用整个屏幕
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_item_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>