I am using RecyclerView Android to make a chat line with left/right message box. I want to set gravity to item of RecyclerView. In normally way, I cast itemView to LinearLayout and then set ParamLayout gravity for it. But if RecyclerView, it seems not right to cast to LinearLayout. It will return RecyclerView.LayoutParams. Because of:
LayoutParams subclass for children of RecyclerView. Custom layout managers are encouraged to create their own subclass of this LayoutParams class to store any additional required per-child view metadata about the layout.
And i can't find the way to set gravity with RecyclerView.LayoutParams :| Anyway, could anybody find the way to gravity item in RecyclerView? Pls suggest me.
-----------POST SOLUTION------------------
//1. Children of RecyclerView
<LinearLayout
android:id="@+id/id_grandparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:divider="@android:color/transparent"
android:gravity="left"
android:orientation="vertical">
<LinearLayout
android:id="@+id/id_llparent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_customer_feedback_left"
android:gravity="left"
android:orientation="vertical">
</LinearLayout>
//2. OnBindView()
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params = setLayoutParamsForParent(params, item.isPosition());
holder.llParentLayout.setLayoutParams(params); //corresponding to id_llparent ID
//3.
private LinearLayout.LayoutParams setLayoutParamsForParent(LinearLayout.LayoutParams params, boolean position) {
params.gravity = position ? Gravity.RIGHT : Gravity.LEFT;
return params;
}
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With