Android连载4-自定义控件的单位和尺寸

一、自定义控件的单位和尺寸

1.一般在PC上会使用px(像素)和pt(磅)作为单位,但是在手机上由于不断地会更新手机屏幕的分辨率,因此使用这两个单位不再那么合适。可能在一部低分辨率手机上,一个控件占据整块屏幕,而在高分辨率的手机屏幕上连一半都占不到。我们先新建一个工程UISizeTest,然后修改activity_main.xml

<RelativeLayout 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" ><Button

      android:id="@+id/button"

      android:layout_width="200px"

      android:layout_height="wrap_content"

      android:text="Button"

      />

 

</RelativeLayout>

既然pt和px不好用,我们可以使用dp和sp来进行设计

二、dp和sp

1.dp是密度无关像素的意思,sp是可伸缩像素的意思,dpi就是屏幕密度,也就是比如一个2*3英寸的屏幕分辨率为320*480像素,那么屏幕的密度就是160dip,代表屏幕每英寸所含有的像素数。

2.使用代码来测量手机的屏幕密度值

 

package com.example.uisizetest;

​

import android.app.Activity;

import android.util.Log;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

​

public class MainActivity extends Activity {

​

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

   

    float xdpi = getResources().getDisplayMetrics().xdpi;

    float ydpi = getResources().getDisplayMetrics().ydpi;

    Log.d("MainActivity","xdpi is "+xdpi);

    Log.d("MainActivity","ydpi is "+ydpi);

  }

​

}

如图:在Logcat中可以看到日志记录的dpi值。

根据Android的规定在160dpi的屏幕上,1dp就等于1px,而在320dpi的屏幕上1dp就等于2px,这样就能保证控件在不用密度的屏幕上显示的比例是一致的。

总结:在Android开发中,如果控件需要指定一个固定值,则使用dp来作为单位,如果指定文字的大小那么使用sp作为单位。

三、源码:

1.项目地址

https://github.com/ruigege66/Android/tree/master/UISizeTest

2.CSDN:https://blog.csdn.net/weixin_44630050

3.博客园:https://www.cnblogs.com/ruigege0000/

4.欢迎关注微信公众号:傅里叶变换,个人公众号,仅用于学习交流,后台回复”礼包“,获取大数据学习资料

原文地址:https://www.cnblogs.com/ruigege0000/p/12683268.html