Android开发

《第二行代码》 第一章 LinearLayout布局

2021-08-24  本文已影响0人  你的益达233

控件我就讲了三个常用的TextView,EditText,ImageView

布局和控件区别:准确说LinearLayout也是控件,因为它里面还能放其他控件,所以我们也可以叫它是布局

单靠控件很难做出复杂的布局,必须结合布局才可以

LinearLayout称作线性布局

1、android:orientation属性设置控件是垂直排列还是横向排列

android:orientation="vertical" 垂直排列
android:orientation="horizontal" 横向排列(默认值)

2、Weight权重

它是设给子控件,用来设置所占LinearLayout的比例

情况一:都设置0dp,这种情况比较简单,就是按比例划分
示例代码:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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"
android:orientation="horizontal"
tools:context=".groupview.LinearLayoutActivity">

<TextView
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="#ff0000"
    android:text="One"
    android:textSize="30sp"
    android:gravity="center"/>

<TextView
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="#00ff00"
    android:text="Two"
    android:textSize="30sp"
    android:gravity="center"/>
</LinearLayout>

效果图:

ll_weight_1.png

情况二:一个wrap_content,一个0dp
先给wrap_content,剩下的空间再按比例再给

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="horizontal"
tools:context=".groupview.LinearLayoutActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="#ff0000"
    android:text="One"
    android:textSize="30sp"
    android:gravity="center"/>

<TextView
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="#00ff00"
    android:text="Two"
    android:textSize="30sp"
    android:gravity="center"/>
</LinearLayout>  

效果图:

ll_weight_2.png

本身One的wrap_content就需要空间,后面剩余空间再按1:1平分

情况二:都是wrap_content
这种情况直接按比例划分

情况三:都是match_parent
这种情况比较复杂,可能有些控件看不见了,显示的比例也可能不是你设置的比例。可以直接放弃掉。记住0dp加设比例情况就好了

3、为LinearLayout中的控件之间设置分割线

这个之前写过一篇文章
https://www.jianshu.com/p/4e5ac4f09f20

上一篇下一篇

猜你喜欢

热点阅读