dimens.xml详解

本文联合两篇博文和自身理解写下
其中一篇:http://blog.csdn.net/hnzcdy/article/details/50628993
另一篇:暂不知原作者
Android中官方建议的屏幕适配方式,通过根据不同的分辨率在工程的res文件夹下建立不同的尺寸文件夹,每个文件夹下都建立dimens.xml文件。然后根据不同的尺寸在dimens.xml文件夹中分别计算配置不同的dp或者sp单位。开发中发现,android屏幕适配需要用到很多的尺寸,每个尺寸都建立dimens.xml问价。每个文件中的数值都要按照比例去计算,一个一个拿着计算器去计算吗?这样太麻烦了。今天有一个好的办法,来为大家介绍一下。

 一、首先我们在工程的res文件夹下,建立不同尺寸的valuse配置文件夹。并在不同的文件夹下建立不同的dimens.xml文件。valuse为默认的工程配置,其余的为根据不同的尺寸适配用户自己新建。(这里以android studio 1.5为示例)

展示
二、 最初在res / values / dimensional.xml中定义的维度的示例自定义(如屏幕边距)用于具有超过820dp可用宽度的屏幕。 这个
将包括在景观中的7“和10”设备(分别〜960dp和〜1280dp)

<?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"> 

<TextView 

android:text="@string/test_dimen" 

android:id="@+id/myDimenTextView01" 

android:layout_width="wrap_content" 

android:layout_height="wrap_content" 

android:width="@dimen/text_width" 

android:height="@dimen/text_height" 

android:background="@color/red_bg" /> 

<Button 

android:text="@string/test_dimen1" 

android:id="@+id/Button01" 

android:layout_width="wrap_content" 

android:layout_height="wrap_content">

</Button>  

</LinearLayout>
Java代码:
package yy.android.dimen;  

import android.app.Activity; 

import android.content.res.Resources; 

import android.os.Bundle; 

import android.widget.Button; 

import com.amaker.test.R; 

public class TestDimensionActivity extends Activity {

private Button myButton; 

@Override 

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); 

// 设置当前Activity的内容布局视图 

setContentView(R.layout.test_dimen); 

// 通过findViewById方法获得Button实例 

myButton = (Button)findViewById(R.id.Button01); 

// 获得Resources 实例 

Resources r = getResources(); 

// 通过getDimension方法获得尺寸值 

float btn_h = r.getDimension(R.dimen.btn_height);

float btn_w = r.getDimension(R.dimen.btn_width);

// 设置按钮的宽 

myButton.setHeight((int)btn_h); 

// 设置按钮的高 

myButton.setWidth((int)btn_w); 

}  

}

posted on 2016-10-27 13:51  木鱼哥  阅读(1176)  评论(0编辑  收藏  举报

导航