2016-09-29 96 views
2

我正在使用RecyclerView其中我有RelativeLayout。在那RelativeLayout,我有一个2 TextView。如果第一个TextView具有某个值,该值决定第二个TextView应该向左还是向右对齐。以编程方式设置布局参数recyclerview的项目

我曾尝试使用下面的代码设置LayoutParamsRecyclerView适配器:

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其他显示评论数左。

+0

如果要求这个小家伙,那么为什么你正在尝试做它在代码中,使用Android:layout_alignWithParentIfMissing =在XML“真”,它将从XML只 – Vickyexpert

+0

管理或偷懒,只是创建两个不同的“TextViews '分开对齐。 – Alpha

回答

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. 

} 
+0

谢谢你的回答,你能告诉我我应该写些什么来代替//在上面代码中的else部分调用requestLayout。 –

相关问题