Android Studio中Logo居中失效求助:使用layout_gravity仍无效
Logo居中问题解决方案
问题原因
android:layout_gravity 属性并不适用于 RelativeLayout,这个属性主要用于 LinearLayout、FrameLayout 这类布局容器的子控件对齐,在 RelativeLayout 中不会生效。
解决方法一:使用 RelativeLayout 自带的居中属性
直接给 ImageView 添加 RelativeLayout 专属的居中属性,替换掉无效的 layout_gravity:
<ImageView android:layout_width="150dp" android:layout_height="150dp" android:src="@drawable/Logo" android:layout_centerInParent="true"/>
修正后的完整布局代码(顺便修复了 EditText 未写完的语法错误):
<?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:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/Background" tools:context=".MainActivity"> <ImageView android:layout_width="150dp" android:layout_height="150dp" android:src="@drawable/Logo" android:layout_centerInParent="true"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/signin" android:text="Sign in" android:textColor="@color/black" android:textSize="35dp" android:textStyle="bold" android:layout_marginTop="150dp" android:gravity="center"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/username" android:hint="Username"/> </RelativeLayout>
注:原代码中
TextView的android:layout_margin="150dp"会同时设置上下左右边距,建议改成android:layout_marginTop="150dp"避免挤压其他控件;EditText 未写完的属性也补充了一个示例。
解决方法二:嵌套 FrameLayout/LinearLayout
如果坚持想用 layout_gravity,可以把 ImageView 放到 FrameLayout 中,FrameLayout 支持该属性:
<FrameLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="150dp" android:layout_height="150dp" android:src="@drawable/Logo" android:layout_gravity="center"/> </FrameLayout>
内容的提问来源于stack exchange,提问作者user21045033
相关产品推荐
相关产品推荐

