Android中长度单位和边距

Android表示单位长度的方式通常有三种表示方式。

  距离单位☞px:表示屏幕实际的象素。例如,320*480的屏幕在横向有320个象素,在纵向有480个象素

  距离单位☞dp:dp = dpi    换算公式:px = dp*(dpi/160)      设置控件大小的通常用dp

  距离单位☞sp(与刻度无关的像素):  会随着用户设置的字体的大小而改变       设置控件的文本大小通常用sp

如果使用dp和sp,系统会根据屏幕密度的变化自动进行转换。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="160dp"
        android:layout_height="100dp"
        android:layout_marginTop="300dp"
        android:layout_marginLeft="0dp"
        android:paddingTop="20dp"
        android:textSize="30sp"
        android:background="#FF0000"
        android:text="@string/hello_world" />

</LinearLayout>
layout_margin(外边距):是控件边缘相对于父控件的边距
 
layout_padding(内边距):是控件内容相对于控件边缘的边距
 
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    
    <Button 
        android:id="@+id/button" 
        android:layout_width="wrap_content"
        android:layout_marginTop="30dp" 
        android:layout_marginLeft="40dp"
        android:layout_marginRight="60dp" 
        android:layout_marginBottom="100dp"
        android:layout_height="wrap_content" 
        android:text="测试按钮一"></Button>

    <Button 
        android:id="@+id/button2" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:paddingLeft="20sp"
        android:paddingTop="5sp" 
        android:text="测试按钮一"></Button>

    <Button 
        android:id="@+id/button3" 
        android:layout_width="wrap_content"
        android:layout_gravity="right" 
        android:layout_height="wrap_content"
        android:text="测试按钮一"></Button>
</LinearLayout>
原文地址:https://www.cnblogs.com/LO-ME/p/3584589.html