当我设计布局时,由于可维护性的主题,我将所有维度集中在 dimens.xml 中。我的问题是这是否正确。最好的做法是什么?这方面的信息很少,什么都没有。我知道将布局的所有字符串集中在strings.xml 上,将颜色集中在colors.xml 上是个好主意。但是关于尺寸?
例如:
<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" />
原文由 Jesús Castro 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用方法
dimens.xml
通过右键单击
values
文件夹并选择 New > Values resource file 创建一个新的dimens.xml
文件。写dimens
作为名称。 (您也可以称它为dimen
或dimensions
。名称并不重要,只有dimen
资源类型将包括在内。)添加
dimen
名称和值。值可以在
dp
、px
或sp
中。或在代码中
何时使用
dimens.xml
感谢 这个答案 以获得更多想法。
重用值- 如果您需要在整个应用程序的多个位置使用相同的维度(例如,Activity 布局填充或 TextView
textSize
),那么使用单个dimen
值即可以后更容易调整。这与使用样式和主题的想法相同。支持多个屏幕-
8dp
的填充在手机上可能看起来不错,但在 10 英寸平板电脑上却很糟糕。您可以创建多个dimens.xml
以用于不同的屏幕。这样您就可以do something like set8dp
for the phone and64dp
for the tablet. To create anotherdimens.xml
file, right click yourres
folder and选择 New > Value resource file 。(有关详细信息,请参阅 此答案)方便
dp
到px
代码转换- 在代码中,您通常需要使用像素值。但是,您仍然必须考虑设备密度,并且以编程方式进行 转换 很烦人。如果您有一个常数dp
值,您可以像float
这样简单地以像素为单位:或者这个
int
:我在 更完整的答案 中提供了更多关于如何做这些事情的细节。
不使用时
dimens.xml
不要将您的值放在
dimens.xml
中,否则会使它们更难维护。一般来说,只要它不属于我上面列出的类别。使用dimens.xml
会使代码更难阅读,因为您必须在两个文件之间来回切换才能查看实际值。个人意见不值得(在我看来)。弦乐不同。所有字符串都应该放在像
strings.xml
这样的资源文件中,因为在国际化您的应用程序时几乎所有字符串都需要翻译。另一方面,大多数维度值不需要针对不同的位置进行更改。 Android Studio 似乎支持这种推理。直接在布局 xml 中定义字符串会发出警告,但定义dp
值不会。