LayoutParams

layoutParams是view用来描述自己在父View中的一些位置参数信息。


<?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"
    tools:context=".MainActivity">


    <LinearLayout
        android:id="@+id/view_r"
        android:layout_width="wrap_content"
        android:layout_height="80dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="32423"
            android:textSize="30sp" />
    </LinearLayout>


</RelativeLayout>


xml布局

这里后去xml中的view,通过getLayoutParams得到的是RelativeLayout.LayoutParams,得知获取的是父view类型的layoutParams。

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout view = findViewById(R.id.view_r);
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params instanceof LinearLayout.LayoutParams) {
            Log.i("jinwei", "LinearLayout");
        } else if (params instanceof RelativeLayout.LayoutParams) {
            Log.i("jinwei", "RelativeLayout");
            RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) view.getLayoutParams();
            p.setMarginStart(200);
            p.addRule(RelativeLayout.ALIGN_START);
        } else if (params instanceof FrameLayout.LayoutParams) {
            Log.i("jinwei", "FrameLayout");
        } else if (params instanceof ViewGroup.MarginLayoutParams) {
            Log.i("jinwei", "MarginLayoutParams");
        }
    }

ViewGroup.LayoutParams
这是顶级的params,它有很多子类params,基本上只要是布局layout都会有一个继承于ViewGroup.LayoutParams的子类。我们可以通过这些LayoutParams,动态多布局设置位置参数了。

    原文作者:金威JW
    原文地址: https://www.jianshu.com/p/dad68fb2b29c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞