Android連載4-自定義控件的單位和尺寸

1、自定義控件的單位和尺寸android

1.通常在PC上會使用px(像素)和pt(磅)做爲單位,可是在手機上因爲不斷地會更新手機屏幕的分辨率,所以使用這兩個單位再也不那麼合適。可能在一部低分辨率手機上,一個控件佔據整塊屏幕,而在高分辨率的手機屏幕上連一半都佔不到。咱們先新建一個工程UISizeTest,而後修改activity_main.xmlgit

<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來進行設計github

2、dp和sp微信

1.dp是密度無關像素的意思,sp是可伸縮像素的意思,dpi就是屏幕密度,也就是好比一個2*3英寸的屏幕分辨率爲320*480像素,那麼屏幕的密度就是160dip,表明屏幕每英寸所含有的像素數。app

2.使用代碼來測量手機的屏幕密度值ide

 

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做爲單位。ui

3、源碼:spa

1.項目地址

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

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

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

4.歡迎關注微信公衆號:傅里葉變換,我的公衆號,僅用於學習交流,後臺回覆」禮包「,獲取大數據學習資料

相關文章
相關標籤/搜索