I have a LinearLayout
and ImageView
, when user receives a message the ImageView
should be on the right and LinearLayout
on it's left, and when sends a message, the ImageView
should be on the left and the LinearLayout
on it's right. how can i do this on runtime?
here is my xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageViewDelivered"
android:layout_width="15sp"
android:layout_height="15sp"
android:src="@drawable/success"
android:layout_gravity="bottom"
android:layout_marginRight="4sp"
android:layout_marginLeft="4sp"
android:layout_marginBottom="2sp"
android:contentDescription="@string/emptytext" />
<LinearLayout
android:id="@+id/contentWithBackground"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="@drawable/incoming_message_bg"
android:paddingLeft="10dp"
android:paddingBottom="10dp"
android:orientation="vertical">
<TextView
android:id="@+id/txtMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="@android:color/black"
android:layout_marginRight="5sp"
android:layout_marginLeft="5sp"
android:maxWidth="250dp" />
</LinearLayout>
</LinearLayout>
thanks.
First change the root layout(which is parent of your LinearLayout
and ImageView
) to RelativeLayout
in your xml file.
Initialize both views:
LinearLayout linear=(LinearLayout)findViewById(R.id.contentWithBackground);
ImageView image=(ImageView)findViewById(R.id.imageViewDelivered);
Initialize the LayoutParam
of LinearLayout
and ImageView
:
RelativeLayout.LayoutParams linearLp=(RelativeLayout.LayoutParams)linear.getLayoutParams();
RelativeLayout.LayoutParams imageLp=(RelativeLayout.LayoutParams)image.getLayoutParams();
To set the LinearLayout
to left of ImageView
:
linearLp.addRule(RelativeLayout.LEFT_OF,image.getId());
To set the LinearLayout
to right of ImageView
:
linearLp.addRule(RelativeLayout.RIGHT_OF,image.getId());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.