TextView居中
- XML
android:layout_gravity = "center";
- Java代码
1.导入包(这里用的是帧布局管理器FrameLayout)
import android.widget.FrameLayout.LayoutParams;
2.实例化TextView
public TextView textView;
textView = new TextView(this);
3.设置布局
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; //设置居中显示
textView.setLayoutParams(params); //设置布局参数
TextView中的文字居中
- XML
android:gravity = "center";
- Java代码
1.导入包
import android.view.Gravity;
2.设置居中
textView.setGravity(Gravity.CENTER);
XML中button布局(LinearLayout)
Activity_main.xml中代码
<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"
android:gravity="center"
android:id="@+id/testlinearlayout"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.android.eggamestart.MainActivity" >
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="layout_gravity:center" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="start"
android:text="gravity:start" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_weight="1" //设置当前组件所占父容器剩余空间的比例
android:layout_height="40px"
android:text="weight" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content" //设置当前组件所占父容器剩余
android:layout_weight="1"
android:layout_height="100px"
android:text="weight" />
</LinearLayout>
- 关于layout_weight属性