简体   繁体   English

如何在Android中使用dimens.xml?

[英]How to use dimens.xml in Android?

When I design a layout, I centralize all dimensions in dimens.xml because of topics of maintainability.当我设计布局时,出于可维护性的考虑,我将所有维度集中在 dimens.xml 中。 My question is if this is correct or not.我的问题是这是否正确。 What would it be the best good practice?最好的做法是什么? There is very little information about this, nothing.关于这方面的信息很少,没有。 I know it's good idea to centralize all strings of a layout on strings.xml, colors on colors.xml.我知道将布局的所有字符串集中在 strings.xml、colors 和 colors.xml 上是个好主意。 But about dimensions?但是关于维度?

For example:例如:

<TableLayout
    android:id="@+id/history_detail_rows_submitted"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/cebroker_history_detail_rows_border"
    android:collapseColumns="*">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/history_detail_rows_margin_vertical"
        android:background="@color/cebroker_history_detail_rows_background"
        android:gravity="center"
        android:paddingBottom="@dimen/history_detail_rows_padding_vertical"
        android:paddingLeft="@dimen/history_detail_rows_padding_horizontal"
        android:paddingRight="@dimen/history_detail_rows_padding_horizontal"
        android:paddingTop="@dimen/history_detail_rows_padding_vertical">

        <TextView
            android:layout_width="match_parent"
            android:drawableLeft="@mipmap/ic_history_detail_submitted_by"
            android:drawablePadding="@dimen/history_detail_rows_textviews_padding_drawable"
            android:gravity="left|center"
            android:paddingRight="@dimen/history_detail_rows_textviews_padding"
            android:text="@string/history_detail_textview_submitted_by"
            android:textColor="@color/cebroker_history_detail_rows_textviews"
            android:textSize="@dimen/history_detail_rows_textviews_text_size" />

How to use dimens.xml如何使用dimens.xml

  1. Create a new dimens.xml file by right clicking the values folder and choosing New > Values resource file .通过右键单击values文件夹并选择新建 > 值资源文件来创建一个新的dimens.xml文件 Write dimens for the name.写下名称的dimens (You could also call it dimen or dimensions . The name doesn't really matter, only the dimen resource type that it will include.) (您也可以将其称为dimendimensions 。名称并不重要,只有它将包含的dimen资源类型。)

  2. Add a dimen name and value.添加dimen名称和值。

     <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="my_value">16dp</dimen> </resources>

    Values can be in dp , px , or sp .值可以是dppxsp

  3. Use the value in xml使用 xml 中的值

     <TextView android:padding="@dimen/my_value" ... />

    or in code或在代码中

     float sizeInPixels = getResources().getDimension(R.dimen.my_value);

When to use dimens.xml何时使用dimens.xml

Thanks to this answer for more ideas.感谢这个答案提供更多想法。

  1. Reusing values - If you need to use the same dimension multiple places throughout your app (for example, Activity layout padding or a TextView textSize ), then using a single dimen value will make it much easier to adjust later.重用值- 如果您需要在整个应用程序中的多个位置使用相同的维度(例如,Activity 布局填充或 TextView textSize ),那么使用单个dimen值将使以后更容易调整。 This is the same idea as using styles and themes.这与使用样式和主题的想法相同。

  2. Supporting Multiple Screens - A padding of 8dp might look fine on a phone but terrible on a 10" tablet. You can create multiple dimens.xml to be used with different screens. That way you could do something like set 8dp for the phone and 64dp for the tablet. To create another dimens.xml file, right click your res folder and choose New > Value resource file . (see this answer for details)支持多屏幕- 8dp的内边距在手机上可能看起来不错,但在 10" 平板电脑上可能很糟糕。您可以创建多个dimens.xml以用于不同的屏幕。这样您就可8dp手机设置8dp64dp用于平板电脑。要创建另一个dimens.xml文件,请右键单击您的res文件夹并选择“新建”>“值资源文件” 。(有关详细信息,请参阅此答案

  3. Convenient dp to px code conversion - In code you usually need to work with pixel values.方便的dppx代码转换- 在代码中,您通常需要处理像素值。 However you still have to think about the device density and the conversion is annoying to do programmatically.但是,您仍然必须考虑设备密度,并且以编程方式进行转换很烦人。 If you have a constant dp value, you can get it in pixels easy like this for float :如果你有一个恒定的dp值,你可以像这样简单地以像素为单位得到它float

     float sizeInPixels = getResources().getDimension(R.dimen.my_value);

    or this for int :或者这对于int

     int sizeInPixels = getResources().getDimensionPixelSize(R.dimen.my_value);

I give many more details of how to do these things in my fuller answer .我在更完整的答案中提供了更多关于如何做这些事情的细节。

When not to use dimens.xml何时不使用dimens.xml

  • Don't put your values in dimens.xml if it is going to make them more difficult to maintain.不要将您的值放在dimens.xml如果这会使它们更难以维护。 Generally that will be whenever it doesn't fall into the categories I listed above.一般来说,只要它不属于我上面列出的类别。 Using dimens.xml makes the code harder to read because you have to flip back and forth between two files to see what the actual values are.使用dimens.xml会使代码更难阅读,因为您必须在两个文件之间来回切换才能查看实际值。 It's not worth it (in my opinion) for individual Views.个人观点不值得(在我看来)。

  • Strings are different.字符串不一样。 All strings should go in a resource file like strings.xml because almost all strings need to be translated when internationalizing your app.所有字符串都应该放在像strings.xml这样的资源文件中,因为在国际化应用程序时几乎所有的字符串都需要翻译。 Most dimension values, on the other hand, do not need to change for a different locality.另一方面,大多数维度值不需要针对不同的位置进行更改。 Android Studio seems to support this reasoning. Android Studio 似乎支持这种推理。 Defining a string directly in the layout xml will give a warning but defining a dp value won't.直接在布局 xml 中定义字符串会给出警告,但定义dp值不会。

add an xml file dimens.xml this is use for support multiple devices.添加一个 xml 文件 dimens.xml 用于支持多个设备。

 <resources>
 <!-- Default screen margins, per the Android Design guidelines. -->
  <dimen name="iconarrow">1dp</dimen>
  <item name="text_view_padding" type="integer">100</item>
</resources>

then you can use it in your code like this in java code然后你可以在你的代码中像这样在java代码中使用它

textview.setPadding(0, 0, 0, getResources().getInteger(R.integer.text_view_padding));

You can also use in other layout(xml file).您也可以在其他布局(xml 文件)中使用。

android:padding="@dimen/text_view_padding"

you don't need to mention dimen value in value folder file.您不需要在值文件夹文件中提及维度值。 this library auto manage all the things you just call like that这个库会自动管理你刚才调用的所有东西

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/_20sdp"
android:paddingLeft="@dimen/_20sdp"
android:paddingRight="@dimen/_20sdp"
android:paddingTop="@dimen/_20sdp"
android:background="@color/colorPrimary"
android:orientation="vertical"
 >

whole code click here for that整个代码点击这里

But about dimensions?

According to the official Android docs "A dimension is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine dimension resources with other simple resources in the one XML file, under one <resources> element"根据Android官方文档“维度是使用name属性中提供的值(而不是XML文件的名称)引用的简单资源。因此,您可以将维度资源与一个XML中的其他简单资源结合起来文件,在一个<resources>元素下”

For more details refer to http://developer.android.com/guide/topics/resources/more-resources.html有关更多详细信息,请参阅http://developer.android.com/guide/topics/resources/more-resources.html

In this post, Devunwired gives three great reasons as to why use dimens.xml When should the dimens.xml file be used in Android?在这篇文章中,Devunwired 给出了为什么使用 dimens.xml 的三个重要原因,什么时候应该在 Android 中使用 dimens.xml 文件?

@Jesús Castro You are doing it right. @Jesús Castro 你做得对。 Maintaining values in the dimens.xml file is better than littering hardcoded values around in all your layout files.在 dimens.xml 文件中维护值比在所有布局文件中乱扔硬编码值要好。

For example, imagine the case where you to increase the left and right margins in all your view.例如,想象一下您在所有视图中增加左右边距的情况。 If you used a single value maintained in dimens.xml, this would be a quick change - a single value in a single file.如果您使用在 dimens.xml 中维护的单个值,这将是一个快速更改 - 单个文件中的单个值。 However, if you had put the margin values as a literal values such as "16dp" in your layout files (instead of using a dimens value like "@dimen/leftright_margin"), you have to go edit each layout file which is error prone and just plain time consuming.但是,如果您在布局文件中将边距值作为文字值(例如“16dp”)(而不是使用像“@dimen/leftright_margin”这样的尺寸值),则必须编辑每个容易出错的布局文件而且很费时间。

I have a novel method I use which I thought is in keeping with the question.我有一种新颖的方法,我认为它与问题保持一致。 I have been avoiding Xml alot to avoid the cost of parsing xml code.我一直在避免使用 Xml 以避免解析 xml 代码的成本。

Rather than using xml dimens ,I use java constants.我没有使用 xml 维度,而是使用 java 常量。 either...任何一个...

public interface DimenConstants { ... }

or...或者...

public class DimenConstants
{
    public static void init(Activity activity){...}
}

Then in the case of supporting different screen, you can actually do this yourself in Java at runtime.那么在支持不同屏幕的情况下,你实际上可以在运行时用Java自己做。 One way is:一种方法是:

public class TestScreenSizes extends Activity
{
    public static final ViewGroup.LayoutParams MAIN_VIEW_SPEC = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

    @Override protected void onCreate(Bundle savedState)
    {
     super.onCreate(savedState);
     setContentView(newTextView(),MAIN_VIEW_SPEC);
    }

    protected TextView newTextView()
    {
     TextView tv = new TextView(this);
     DisplayMetrics display = getResources().getDisplayMetrics();

     int resolution = display.widthPixels * display.heightPixels;

     if(resolution == 1024) tv.setText("You are using an iphone");
     else if(resolution == 4096) tv.setText("You are using a Samsung Galexy");

     return rv;
    }
}

yes absolutely It is best to keep the values in the dimens.xml file yes absolutely 最好将值保留在 dimens.xml 文件中

I don't know if it can help you but I wrote a little java programe that allows you to duplicate a dimension xml file with a new desired value so that you no longer have to do it by hand line by line.我不知道它是否可以帮助你,但我写了一个小的 java 程序,它允许你用一个新的期望值复制一个维度 xml 文件,这样你就不再需要逐行手工完成。

https://github.com/Drex-xdev/Dimensions-Scalable-Android https://github.com/Drex-xdev/Dimensions-Scalable-Android

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM