How To Make List View Items Align Left And Right Programmatically In Android
Solution 1:
You should set your layout_gravity
to left or right, instead of the gravity
.
I'm copying the concept from How to set layout_gravity programmatically?
Example (warning, code is not tested):
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
if(hashMap.get("is_mine").equals("yes")) {
layout.setBackgroundResource(R.drawable.bg_msg1);
params.gravity = Gravity.RIGHT;
parent_layout.setParams(params);
} else {
layout.setBackgroundResource(R.drawable.bg_msg2);
params.gravity = Gravity.LEFT;
parent_layout.setParams(params);
parent_layout.setGravity(Gravity.LEFT);
}
Alternatively, you make 2 different XMLs and assign layout_gravity
inside the xml itself, and inflate appropriate layout for each row.
Solution 2:
Use two different textview left and right for is_mine if is_mine is yes set visbility GONE for the other one and set your text on that textview and vice versa.
Solution 3:
Instead of using listview try using dynamic textview : create new Linear layout like
Lineqarlayout ll =newLinear Layout();
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tvIncoming=new TextView(this);
tvIncoming.setLayoutParams(lparams);
tvIncoming.setGravity(GRAVITY.RIGHT);
tvIncoming.setText("test");
this.ll.addView(tv);
//similarly tvOutgoing with gravity leftif(hashMap.get("is_mine").equals("yes")) {
tvOutgoing.setBackgroundResource(R.drawable.bg_msg1);
holder.txtMsg.setText(hashMap.get("message"));
} else {
tvincogoing.setBackgroundResource(R.drawable.bg_msg1);
holder.txtMsg.setText(hashMap.get("message"));
}
Let me know if it helps::) Edit: Use this code(or pseudocode ) in your activity and not in adapter
Solution 4:
In your Layout folder, you should create 2 different xml files: rightchatbubble.xml and leftchatbubble.xml with android:layout_gravity="right" and android:layout_gravity="left" respectively.
In your Adapter you should change the following:
if(hashMap.get("is_mine").equals("yes")) {
layout.setBackgroundResource(R.drawable.bg_msg1);
parent_layout.setGravity(Gravity.RIGHT);
} else {
layout.setBackgroundResource(R.drawable.bg_msg2);
parent_layout.setGravity(Gravity.LEFT);
}
with:
if (hashMap.get("is_mine").equals("yes")) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.leftchatbubble, parent, false);
}
else {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.rightchatbubble, parent, false);
}
and it should work fine. Obviously, in the main remember to update
YOURadapter.notifyDataSetChanged();
Post a Comment for "How To Make List View Items Align Left And Right Programmatically In Android"