android layout_gravity失效的问题

相信对于Android的初学者来说,大家都曾经被layout里这两个极其相似的属性迷惑过。
简单使用一下搜索工具,我们就不难找到下面这样的答案:

layout_gravity 表示组件自身在父组件中的位置
gravity 表示组件的子组件在组件中的位置

看似很简单嘛

为什么这么简单的道理,总有同学会发现,在“某些时候”,layout_gravity这个属性不好使了,失去了它应有的作用

问题究竟出在哪里了呢?

当作为父layout的LinearLayout的属性为android:orientation="vertical"的时候,android:layout_gravity="?"这里设为横向的时候才能生效。比如:left,right,center_horizontal等;
当作为父layout的LinearLayout的属性为android:orientation="horizental"的时候,android:layout_gravity="?"这里设为纵向的时候才能生效。比如:top,bottom,center_vertical等;
有一个比较特殊的是center,不管是横向还是纵向的时候,它总有一个方向起作用, 因为LinearLayout他只可能有一个方向,

这nm的,确实让人蛋疼。其实也有点道理吧,就是LinearLayout横向的时候,如果有多个孩子,那就不知道把谁放最右了,

有两个解决方法吧,

(1)用RelativeLayout吧,这个算是费话吧 ,哈哈

(2)在LinearLayout中设置android:gravity这个从官方api的解释是怎么放置它的内容,LinearLayout的内容不就是他的孩子么,问题解决


博客来源:xiaoQLu

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ModbusConnectActivity"> <!-- 添加一个 LinearLayout 来放置照片、显示框和按钮 --> <LinearLayout android:id="@+id/topLayout" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:padding="16dp" android:layout_marginBottom="8dp"> <!-- 用于与下面的 FrameLayout 保持间隔 --> <!-- 照片显示框 --> <ImageView android:id="@+id/photoImageView" android:layout_width="100dp" android:layout_height="50dp" android:src="@drawable/tu2" android:contentDescription="Photo" android:layout_marginEnd="16dp" /> <!-- 显示框 --> <TextView android:id="@+id/displayTextView" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Your Text Here" android:textSize="16sp" android:gravity="center_vertical" android:paddingEnd="16dp" /> <!-- 按钮 --> <Button android:id="@+id/actionButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="获取TCU地址" android:onClick="onButtonClick" /> <!-- 自定义按钮点击事件 --> </LinearLayout> <FrameLayout android:id="@+id/content" android:layout_above="@id/bottomNavigationView" android:layout_width="match_parent" android:background="@drawable/bg" android:layout_height="match_parent"/> <!-- 底部导航栏 --> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottomNavigationView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" app:menu="@menu/navigation" app:labelVisibilityMode="labeled"/> </RelativeLayout>将LinearLayout与FrameLayout隔开
最新发布
03-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值