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

时间:2016-09-29 05:36:55

标签: android android-relativelayout

我正在使用RecyclerView我有一个RelativeLayout。在那RelativeLayout中,我有一个TextView。如果第一个TextView具有某个值,该值决定第二个TextView是否应该向右或向左对齐。

我已使用以下代码在LayoutParams适配器中设置了RecyclerView

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,那么所有其他项目也会对齐到左边。

我想将评论计数显示为右,如果count > 0其他显示评论计数左侧。

1 个答案:

答案 0 :(得分:2)

这两个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. 

}