Set gravity programmatically for item in RecycerView Android

心不动则不痛 提交于 2019-12-04 09:47:09

I did that by setting the gravity on the view inside the item's layout.

LinearLayout.LayoutParams paramsMsg = new LinearLayout.
            LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    if (position%2 == 0){
        holder.bodyView.setBackgroundResource(R.drawable.outgoing_messages);
        paramsMsg.gravity = Gravity.END;
    } else {
        holder.bodyView.setBackgroundResource(R.drawable.incoming_messages);
        holder.bodyView.setTextColor(0xf08888);
        paramsMsg.gravity = Gravity.START;
    }
    holder.bodyView.setLayoutParams(paramsMsg);

bodyView is the TextView inside the item's Layout and the item width is "match_parent".

Problem solved. Simply, I using

 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

instead of

RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) holder.llGrandParent.getLayoutParams();

And then set gravity for LinearLayout Params normally.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!