Abh*_*bhi 2 android android-recyclerview android-constraintlayout
缩小工作布局代码,
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/recyclerview_item_layout_root_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textview.MaterialTextView
android:id="@+id/recyclerview_item_layout_textview_fact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)
上面的代码按预期呈现回收器视图。
但根据文档,
您不能对 ConstraintLayout 中的任何视图使用 match_parent。而是使用“匹配约束”(0dp)。
所以,我替换了这一行,
android:layout_width="match_parent"
Run Code Online (Sandbox Code Playgroud)
有了这个
android:layout_width="0dp"
Run Code Online (Sandbox Code Playgroud)
但是,它不起作用。是recyclerview不可见的。
完整的存储库是开源的, https://github.com/Abhimanyu14/cat-fact
Recyclerview 适配器代码(如果需要),
class HomeFragmentRecyclerViewAdapter :
PagingDataAdapter<CatFact, HomeFragmentRecyclerViewAdapter.MainActivityRecyclerViewHolder>(
CatFactDiffCallback
) {
class MainActivityRecyclerViewHolder(private var binding: RecyclerviewItemLayoutBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(catFact: CatFact?) {
catFact?.let {
binding.recyclerviewItemLayoutTextviewFact.text = String.format(
binding.root.context.resources.getString(R.string.recyclerview_item_layout_fact),
catFact.id,
catFact.fact
)
}
}
}
object CatFactDiffCallback : DiffUtil.ItemCallback<CatFact>() {
override fun areItemsTheSame(oldItem: CatFact, newItem: CatFact): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: CatFact, newItem: CatFact): Boolean {
return oldItem == newItem
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): MainActivityRecyclerViewHolder {
return MainActivityRecyclerViewHolder(
RecyclerviewItemLayoutBinding.inflate(
LayoutInflater.from(
parent.context
)
)
)
}
override fun onBindViewHolder(holder: MainActivityRecyclerViewHolder, position: Int) {
holder.bind(getItem(position))
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所说,文档说:
您不能对 ConstraintLayout 中的任何视图使用 match_parent。而是使用“匹配约束”(0dp)。
文档过去还说结果是不可预测的。我想“不可预测”意味着“它有效”(有时)。
使用0dp是正确的。您遇到的问题是,您正在膨胀的视图需要对其父视图的引用才能知道它有多大,因此您需要提供父引用(下面膨胀中的第二个参数),但不将膨胀的视图附加到父视图(第三个参数),因为RecyclerView会处理这个问题。
return MainActivityRecyclerViewHolder( RecyclerviewItemLayoutBinding
.inflate( LayoutInflater.from( parent.context ), parent, false )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3166 次 |
| 最近记录: |