【发布时间】:2016-07-10 10:49:08
【问题描述】:
我正在尝试使用新的 ConstraintLayout。我为我的 RecyclerView 的行做了布局。它有 ConstraintLayout 作为根元素,其宽度设置为 match_parent,当我运行我的应用程序时,它会按预期呈现
在我将数据绑定部分放入我的 XML 之前它运行良好,并且根元素此后是 layout 标记,它包装了 ConstraintLayout 并导致 ConstraintLayout 的行为发生一些不可预测的变化 - 它的宽度今后不会呈现为 @987654327 @,它只占显示宽度的一小部分,尽管它在 XML 中仍然设置为 match_parent。我也尝试将宽度设置为某个固定值,结果是一样的
我怀疑数据绑定处理器在构建过程中处理布局时会从 ConstrainLayout 中剥离属性。有什么方法可以让事情正常工作吗? 我的布局
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<import type="android.view.View"/>
<variable
name="post"
type=".entity.Post"/>
<variable
name="data"
type=".entity.LinkPostData"/>
</data>
<android.support.constraint.ConstraintLayout
android:id="@+id/constraintLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="16dp">
....
</android.support.constraint.ConstraintLayout>
</layout>
和适配器:
class PostsAdapter(): RecyclerView.Adapter<PostsAdapter.PostItemViewHolder>() {
private val posts: MutableList<Post> = ArrayList()
fun setPosts(domains: List<Post>) {
this.posts.clear()
this.posts.addAll(domains)
notifyDataSetChanged()
}
override fun getItemViewType(position: Int): Int {
return super.getItemViewType(position)
}
override fun onBindViewHolder(holder: PostItemViewHolder?, position: Int) {
val post = posts[position]
holder?.binding?.post = post
holder?.binding?.data = post.data as LinkPostData
holder?.binding?.executePendingBindings()
}
override fun getItemCount() = this.posts.size
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): PostItemViewHolder {
val binding = ItemPostBinding.inflate(LayoutInflater.from(parent?.context))
return PostItemViewHolder(binding)
}
class PostItemViewHolder(val binding: ItemPostBinding): RecyclerView.ViewHolder(binding.root) {
}
}
【问题讨论】:
-
您能否发布您的布局
xml,以及您的Adapter和RecyclerView的相关代码? -
我编辑了我的问题,但找到了原因——DataBinding 和
ConstraintLayout不兼容,问题是如何让它一起工作 -
我可以告诉你,数据绑定绝对不是问题。自发布以来,我一直在使用数据绑定和约束布局,并且从未遇到任何问题。而且他们也不是真的有任何问题。数据绑定通过从您编写的文件生成一个新的普通布局文件来工作。您实际上可以在构建文件夹中查看它。在某处生成。
-
顺便说一句:您应该将所有命名空间声明移动到布局标签。您正在约束布局上声明 android 命名空间。
-
@XaverKapeller 感谢分享。最后我设法找出问题的真正原因
标签: android android-databinding android-constraintlayout