Android自定義控件單位尺寸實(shí)現(xiàn)代碼
一、自定義控件的單位和尺寸
1.一般在PC上會使用px(像素)和pt(磅)作為單位,但是在手機(jī)上由于不斷地會更新手機(jī)屏幕的分辨率,因此使用這兩個單位不再那么合適。可能在一部低分辨率手機(jī)上,一個控件占據(jù)整塊屏幕,而在高分辨率的手機(jī)屏幕上連一半都占不到。我們先新建一個工程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: android:layout_width='200px' android:layout_height='wrap_content' android:text='Button' /></RelativeLayout>
既然pt和px不好用,我們可以使用dp和sp來進(jìn)行設(shè)計(jì)
二、dp和sp
1.dp是密度無關(guān)像素的意思,sp是可伸縮像素的意思,dpi就是屏幕密度,也就是比如一個2*3英寸的屏幕分辨率為320*480像素,那么屏幕的密度就是160dip,代表屏幕每英寸所含有的像素?cái)?shù)。
2.使用代碼來測量手機(jī)的屏幕密度值
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值。
根據(jù)Android的規(guī)定在160dpi的屏幕上,1dp就等于1px,而在320dpi的屏幕上1dp就等于2px,這樣就能保證控件在不用密度的屏幕上顯示的比例是一致的。
總結(jié):在Android開發(fā)中,如果控件需要指定一個固定值,則使用dp來作為單位,如果指定文字的大小那么使用sp作為單位。
三、源碼:
項(xiàng)目地址
https://github.com/ruigege66/Android/tree/master/UISizeTest
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
