Search code examples
androidkotlinandroid-layout

How to force the app to open in custom "minimum width"


so i have my phone that is set to "minimum width of" 384dp (in developers options), what i want to do is to open my android studio app like if the phone had its minimum width of 478dp.

is there any way to do it besides to make a different type of layouts for different screens size? maybe to write a code in OnCreate?

enter image description here


Solution

  • class MainActivity : AppCompatActivity(), QuantityListener {
    override fun onCreate(savedInstanceState: Bundle?) {
    
            super.onCreate(savedInstanceState)
    
            val changeddp = 478
            overrideDensity(changeddp)
            //^^^^before setting the layout(in my case test2), change the width.
            setContentView(R.layout.test2)
            }
    }
        private fun overrideDensity(changeddp: Int) {
            val resources = resources
            val configuration = resources.configuration
            val screenwidthPx = resources.displayMetrics.widthPixels
            val newDensity = screenwidthPx.toFloat() / changeddp
            configuration.densityDpi = (newDensity * 160).toInt()
            resources.updateConfiguration(configuration, resources.displayMetrics)
        }