Android FrameLayout布局中的控件设置居中动态设置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhao2017/article/details/84561074

Android FrameLayout 布局文件静态设置里面的控件时是默认左上角叠加的。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@color/black">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HelloWorld"
        android:textColor="@color/white"
        android:textSize="18sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is HelloWorld"
        android:textColor="@color/white"
        android:textSize="18sp" />

</FrameLayout>

静态布局文件设置居中时只需要設置里面控件的layout_gravity:

 <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="This is HelloWorld"
        android:textColor="@color/white"
        android:textSize="18sp" />

代码中动态设置。(动态添加控件的处理方案):

   FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) textView.getLayoutParams();
            // 设置里面的控件的布局和父布局的高度相同   
            layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
            textView.setLayoutParams(layoutParams);
            // 设置控件自身的内容居中
            textView.setGravity(Gravity.CENTER );

猜你喜欢

转载自blog.csdn.net/zhao2017/article/details/84561074
今日推荐