How can I use layout_width using resource file?

Viewed 10434

There are a activity what I want to fill the screen in a phone and pop up(dialog) for a tablet.

I thought I make a layout file like this,

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="@dimen/main_layout_width"
  android:layout_height="match_parent">

and externalize the value of width as

in values/dimens.xml

<dimen name="tutorial_width">match_parent</dimen>

in values-xlarge/dimens.xml

<dimen name="tutorial_width">320dp</dimen>

But I can't representation 'match_parent' as dimen element. Any help? Thanks!

9 Answers

The best way I found: - instead of "match_parent" and "fill_parent" write "-1dp" - instead of "wrap_content" write "-2dp"

Value -1 was not working for me on android api 30 emulator of Pixel 4.

Clean solution is to define sw600dp/styles.xml and create base style for your component in styles f.e. DialogControllerTypeGridBase then create other that ha its as parent DialogControllerTypeGrid and also other in sw600dp.

Example:

styles.xml

<style name="DialogControllerTypeGridBase" parent="CSGridMatch">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:background">@drawable/background_bordered_section</item>
    <item name="android:horizontalSpacing">8dp</item>
    <item name="android:padding">4dp</item>
    <item name="android:verticalSpacing">8dp</item>
</style>

<style name="DialogControllerTypeGrid" parent="DialogControllerTypeGridBase">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:numColumns">6</item>
</style>

sw600dp/styles.xml

 <style name="DialogControllerTypeGrid" parent="DialogControllerTypeGridBase">
        <item name="android:layout_width">450dp</item>
        <item name="android:numColumns">3</item>
 </style>

This way nothing gets duplicated and you dont use meaningles values like -1, -2 that dont work reliably across device based not just by me but also comments from others.

Related