如何将整个TextView(非内部文本)对齐到父LinearLayout右侧,适配聊天应用
解决方案
- 方案1:仅调整需要右对齐的单个TextView,适合聊天场景同时存在左右两种消息的情况
给TextView添加android:layout_gravity="end"属性即可,该属性控制子控件在父LinearLayout中的对齐方向,使用end而非right可以更好适配阿拉伯语等从右到左的系统语言场景。
修改后的XML代码如下:
<LinearLayout android:id="@+id/chatMessages" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end" android:layout_marginLeft="10dp" android:layout_marginTop="20dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:background="@drawable/background2" android:text="Losowy tekst" android:textSize="25sp"> <!-- 优化提示:文本大小推荐用sp而非dp,会跟随系统字体大小设置调整,体验更友好 --> </TextView> </LinearLayout>
- 方案2:如果当前LinearLayout内所有子控件都需要右对齐,可以直接给父LinearLayout添加
android:gravity="end"属性,无需修改每个子View的配置:
<LinearLayout android:id="@+id/chatMessages" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="end"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="20dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:background="@drawable/background2" android:text="Losowy tekst" android:textSize="25sp"> </TextView> </LinearLayout>
内容的提问来源于stack exchange,提问作者Igorson
相关产品推荐
相关产品推荐

