Android中如何让控件居中
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android中如何让控件居中相关的知识,希望对你有一定的参考价值。
方法一:设置父布局的属性,但是framelayout是没有居中效果的
线性布局linearlayout和相对布局relativelayout比较常用
下面是两个textview在LinearLayout线性布局下的效果
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text2" />
</LinearLayout>
可以看到两个textview居中了
在RelativeLayout中同样的效果
方法二:单独设置view的居中属性为
在linearlayout中只能是布局方向居中,设置android:layout_gravity属性
如
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"
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:text="text1"
android:layout_gravity="center"
android:textSize="30sp" />
</LinearLayout>
可以看到只有横向居中
在Relativelayout中设置android:layout_inParent属性为true
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text1"
android:layout_centerInParent="true"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text2"
android:textSize="30sp" />
</RelativeLayout>
可以看到只有textview1是居中的
以上是关于Android中如何让控件居中的主要内容,如果未能解决你的问题,请参考以下文章
android 不居中界面限制了控件个数,控件太多就满了怎么办,附图,最后一行
Android开发,如何让PopupWindow弹出时外部控件不可点击?
android 代码中设置控件的垂直居中和两个控件之间的距离。