以编程方式设置RecyclerView项的布局参数

4
我正在使用RecyclerView,其中我有一个RelativeLayout。在那个RelativeLayout中,我有2个TextView。如果第一个TextView有一些值,这决定了第二个TextView是否应该对齐到右侧或左侧。
我已经使用以下代码在RecyclerView适配器中设置了LayoutParams:
if (listItem.getmLikeCount() > 0) {
    RelativeLayout.LayoutParams feedCommentParams = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    feedCommentParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
    listItemHolder.mCommentCount.setLayoutParams(feedCommentParams);
} else {
    listItemHolder.mLikeCount.setVisibility(View.GONE);
    RelativeLayout.LayoutParams feedCommentParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    feedCommentParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
    listItemHolder.mCommentCount.setLayoutParams(feedCommentParams);
}

但是这些项目正在进行回收,即如果任何一个RecyclerView项目没有任何计数,则所有其他项目也会对齐到左侧。
如果喜欢count > 0,则将评论计数显示到右侧,否则将评论计数显示到左侧。

如果需求很简单,为什么要在代码中实现呢?在xml中使用android:layout_alignWithParentIfMissing="true",它会在xml中自动处理。 - Vickyexpert
或者懒一点,只需创建两个不同的“TextView”,并分别对齐。 - Alpha
1个回答

3
问题可以通过将两个TextView分别对齐来轻松解决。因此,根据评论计数,您可以将它们的可见性设置为GONEVISIBLE
无论如何,在您的情况下,您可能需要在if和else语句中调用requestLayout,就像这样。
if (listItem.getmLikeCount() > 0) {
    RelativeLayout.LayoutParams feedCommentParams = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    feedCommentParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
    listItemHolder.mCommentCount.setLayoutParams(feedCommentParams);

    // Call requestLayout here 

} else {
    listItemHolder.mLikeCount.setVisibility(View.GONE);
    RelativeLayout.LayoutParams feedCommentParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    feedCommentParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
    listItemHolder.mCommentCount.setLayoutParams(feedCommentParams);

    // Call requestLayout here for the else part. 

}

谢谢你的回答,你能告诉我在上面代码的else部分,我应该写什么来代替// Call requestLayout here吗? - Prithniraj Nicyone

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接