'Android - Wrong dimen values are used when passing from portrait to landscape

I have a custom component and my problem is;

  • when I open my fragment in Tablet in Portrait, it uses true dimen value 72dp (which is in my values-sw600dp folder) but when I rotate to Landscape, it still uses this value. But I have values-sw600dp-land folder and value is 160dp.
  • when I open my fragment in Tablet in Landscape, it uses true dimen value 160dp (which is in my values-sw600dp-land folder) but when I rotate to Portrait, it still uses this value. But I have values-sw600dp folder and value is 72dp.

I use custom component in my fragment's xml like this:

<com.myexample.StorageBar
    android:id="@+id/storage_bar"
    style="@style/Download.Storage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Its style is written in my styles.xml file like;

<style name="Download.Storage">
    <item name="android:paddingLeft">@dimen/download_storage_footer_gutter</item>
    <item name="android:paddingRight">@dimen/download_storage_footer_gutter</item>
  </style>

And the dimen values are in;

  • values-sw600dp folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <dimen name="download_storage_footer_gutter">72dp</dimen>
</resources>

  • values-sw600dp-land folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <dimen name="download_storage_footer_gutter">160dp</dimen>
</resources>

If I add these lines in to my fragment.kt file, works perfectly:

override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    if(newConfig.orientation == 1){
        val paddingDp = 72
        val density = requireContext().resources.displayMetrics.density
        val paddingPixel = (paddingDp * density).toInt()
        storage_bar.setPadding(paddingPixel,0,paddingPixel,0)
    }
    else{
        val paddingDp = 160
        val density = requireContext().resources.displayMetrics.density
        val paddingPixel = (paddingDp * density).toInt()
        storage_bar.setPadding(paddingPixel,0,paddingPixel,0)
    }
}

but I don't want to solve it by programmatically. How can I solve these?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source