Is it possible in android to define constants in XML that vary with configuration

风格不统一 提交于 2020-01-12 06:30:10

问题


I am interested in having an XML layouts in Android change size depending on landscape or portrait viewing (and maybe other configurations later).

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_alignParentBottom="true"
android:background="@drawable/stream_bg_1px_wide"
android:layout_height="150dip" >

In this example I just want to vary the 150dip size depending on landscape or portrait, not change anything else.

I am using layout and layout-land, and I know I could repeat the layout in each of those folders, but that makes maintaining changes in it a bit of a pain. When I introduce more variants based on screen density and size it just gets worse.

So, I wondered if it's possible to define a value (constant) in an XML file, and reference it from my layout, similar to how colors can be defined

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="shopper_background"> #FFFFFF</color>
</resources>

along the lines of......

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <value name="footer_size" >150</value>
</resources>

Then I could just replicate that file, with different values, in each config.

thanks for any help


回答1:


Yes. A dimension is an accepted item in a resource file. So create e.g. res/values/dimension.xml and put

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



回答2:


Yes you can do this, we do it all over the place in Android itself :) Just define your constants in res/values/, res/values-land/ etc. For dimensions, use the tag and refer to them using @dimen/my_value in the layout.



来源:https://stackoverflow.com/questions/5285429/is-it-possible-in-android-to-define-constants-in-xml-that-vary-with-configuratio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!