安卓笔记 day4

146 阅读1分钟

设置视图的宽高

各种设置视图宽高的方法

1.在Xml中设置

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="wrap_content(跟随内容)"
    android:textColor="#ffffff"
    android:background="#000000"/>
<!--'wrap_content'意为跟随内容,就是内容多大它多大-->
<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="match_parent(匹配父项)"
    android:textColor="#ffffff"
    android:background="#000000"/>
<!--'match_parent'意为匹配父项,就是父控件多大它多大-->
<TextView
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:text="300dp(固定尺寸)"
    android:textColor="#ffffff"
    android:background="#000000"/>
<!--'300dp'就是(300*dip/160)个px-->
<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="用java设置宽高"
    android:textColor="#ffffff"
    android:background="#000000"/>
<!--java代码见下方-->

2.在Java中设置

    TextView tv1 = findViewById(R.id.tv1);
    ViewGroup.LayoutParams params = tv1.getLayoutParams();
    // 获取tv1的布局参数(含宽高)
    params.width = 300;
    //设置tv1的布局参数,这里的300意思是300px
    tv1.setLayoutParams(params);

设置视图的边距

外边距

1.在Xml中设置

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="30dp"
    android:text="layout_margin(布局边距)"
    android:textColor="#ffffff"
    android:background="#000000"/>
<!--'layout_margin'意为布局边距,就是外边距-->
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_marginBottom="30dp"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="30dp"
    android:text="Top_Bottom_Left_Right"
    android:textColor="#ffffff"
    android:background="#000000"/>
<!--还可以使用不同方位的外边距-->

2.在Java中设置

    LinearLayout.LayoutParams mp = (LinearLayout.LayoutParams)tv1.getLayoutParams()
    // 获取tv1的线性布局参数
    int marginsdp = Fun.fun.dptopx(this,30);
    // 存放要设置的边距尺寸
    mp.setMargins(marginsdp,marginsdp,marginsdp,marginsdp);
    // 设置tv1的外边距

内边距

1.在Xml中设置

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="30dp"
    android:text="padding(填充)"
    android:textColor="#ffffff"
    android:background="#000000"/>
<!--'padding'意为填充,就是内边距-->
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="30dp"
    android:paddingBottom="30dp"
    android:paddingLeft="30dp"
    android:paddingRight="30dp"
    android:text="Top_Bottom_Left_Right"
    android:textColor="#ffffff"
    android:background="#000000"/>
<!--还可以使用不同方位的内边距-->

2.在Java中设置

    tv1.setPadding(30,30,30,30);