Android日常开发 - FlexboxLayout学习笔记
Android日常开发使用FlexboxLayout实现流式布局的效果,FlexboxLayout与h5中的flex使用十分相似,都是将父元素设置成flex布局,通过设置属性,使子元素实现不同的排列
1、h5中的flex布局(弹性布局)使用
定义一个场景:body下面有两个div,div的宽高均为300px,margin-left为100px,代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
/* 设置div的宽高和左边距 */
.content,.navigation{
width: 300px;
height: 300px;
background-color: palevioletred;
margin-left: 100px;
}
</style>
</head>
<body>
<div class="content">
</div>
<div class="navigation">
</div>
</body>
</html>
flex-direction属性
设置body下的元素排列方向。row,表示横向排列;cloumn,表示为纵向排列。设置横向排列,代码如下
<style>
body{
display: flex;
flex-direction: row;
}
</style>
效果
justify-content属性
设置body下元素在当前排列方向的对齐方式。flex_start为左对齐;center为居中;flex_end为右对齐。设置为居中对齐,代码如下
<style>
body{
display: flex;
flex-direction: row;
justify-content: center;
}
</style>
效果
align-items
设置body下元素在非当前排列方向(如果排列方向是横向排列,设置的是纵向,反之就是横向)的对齐方式。flex_start为左对齐;center为居中;flex_end为右对齐。横向排列的情况下设置元素在纵向为居中对齐,代码如下
<style>
body{
display: flex;
flex-direction: row;
height: 1000px;
align-items: center;
}
</style>
效果
2、Android中使用FlexboxLayout
添加依赖
implementation 'com.google.android:flexbox:1.0.0'
使用须知
FlexboxLayout下面添加需要展示的子布局;FlexboxLayout相比较RecyclerView的优势是根据可以子View的宽度自动换行
注意点
-
FlexboxLayout中,必须要设置flexWarp属性为wrap,否则多个元素超过父布局的宽高后不会自动换行!
-
flexDirection对应h5中的flex_direction
-
justifyContent对应h5中的justify_content
-
alignItems对应h5中的align_items
设置布局文件
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.flexbox.FlexboxLayout 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:id="@+id/flexbox_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".flex.FlexboxLayoutDemoActivity"
app:flexWrap="wrap"
app:flexDirection="row"
app:justifyContent="flex_start"
app:alignItems="center"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:background="@color/white">
<!--子View部分省略-->
</com.google.android.flexbox.FlexboxLayout>
效果
其他地方使用的效果
参考文章