尺寸资源
(1)认识dp
主布局(activity_main.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View android:background="@color/red" android:layout_width="10dp" android:layout_height="50dp"/>
<View android:background="@color/green" android:layout_width="20dp" android:layout_height="50dp"/>
<View android:background="@color/blue" android:layout_width="30dp" android:layout_height="50dp"/>
<View android:background="#FFFF00FF" android:layout_width="40dp" android:layout_height="50dp"/>
</LinearLayout>
运行结果:
说明:
dp是一种长度单位,与屏幕的像素密度有关系(若设备为160px/英寸,则dp=px),主要用于描述组件宽高。
此外,类似的长度单位还有sp(主要描述文字,为比例大小)、pt(描述文字大小,意为磅)、mm(毫米)、in(英寸)、px(像素)。
(2)在values下新建XML文件,命名为dimen。
原来的values文件中本来就有一个文件叫做dimens,在其中补充写入代码
<dimen name="dp10">10dp</dimen>
在主布局文件中使用它(dp10)
<View android:background="@color/red" android:layout_width="@dimen/dp10" android:layout_height="50dp"/>
运行程序,效果相同。