大部分UI组件都是继承于android.view.View
,因此学好视图基础,可以应对大部分的组件。
视图的宽高
视图端:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_width="300dp"
android:layout_height="300dp"
wrap_content
:包裹内容,内容多大,视图多大,如果超过父级的宽度会被隐藏。
match_parent: 匹配父级,父级元素的宽度就是最大宽度。
300dp:也可直接设定固定尺寸。
JAVA端设置:
// Activity
// 获取视图中的空间
TextView tvone = findViewById(R.id.tvone);
// 获取视图布局配置文件
ViewGroup.LayoutParams params = tvone.getLayoutParams();
// 这块这只的30是px,需要转成成dp
// params.width = 30;
params.width = Utils.dp2px(this,300)
// 设置布局配置文件
tvone.setLayoutParams(params);
// 工具类中的转换函数
public static int dp2px(Context context, float dpValue){
// 获取手机当前的像素密度 一个dp对应几个px
float scale = context.getResources().getDisplayMetrics().density;
// 四舍五入取整
return (int) (scale * dpValue + 0.5f);
}
视图的间距
android:layout_margin="20dp"
android:padding="60dp"
layout_margin: 外边距,当前视图距离同级视图直接的距离。
padding:内边距,当前视图距离最近子元素之前的距离。
Demo:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#00ff99"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:background="#0099ff"
android:padding="60dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000"></LinearLayout>
</LinearLayout>
</LinearLayout>
视图的对齐
android:layout_gravity="bottom"
android:layout_gravity="left|bottom"
android:gravity="left|bottom"
android:gravity="left"
layout_gravity: 相对于父级元素的定位
gravity:内部子元素的定位。
Demo:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="@color/green"
android:orientation="horizontal">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="200dp"
android:layout_margin="10dp"
android:layout_weight="1"
android:background="#0099cc"
android:orientation="horizontal"
android:padding="10dp" android:layout_gravity="bottom" android:gravity="left|bottom">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#cc9900"></View>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="200dp"
android:layout_margin="10dp"
android:layout_weight="1"
android:background="#0099cc"
android:orientation="horizontal"
android:padding="10dp" android:layout_gravity="top" android:gravity="right">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#cc9900"></View>
</LinearLayout>
</LinearLayout>