Load dimension value from res/values/dimension.xml from source code

前端 未结 9 1665
情书的邮戳
情书的邮戳 2020-11-27 09:30

I\'d like to load the value as it is. I have two dimension.xml files, one in /res/values/dimension.xml and the other one in /res/values-sw360

相关标签:
9条回答
  • 2020-11-27 10:07
    Context.getResources().getDimension(int id);
    
    0 讨论(0)
  • 2020-11-27 10:08

    You can write integer in xml file also..
    have you seen [this] http://developer.android.com/guide/topics/resources/more-resources.html#Integer ? use as .

     context.getResources().getInteger(R.integer.height_pop);
    
    0 讨论(0)
  • 2020-11-27 10:09

    Use a Kotlin Extension

    You can add an extension to simplify this process. It enables you to just call context.dp(R.dimen. tutorial_cross_marginTop) to get the Float value

    fun Context.px(@DimenRes dimen: Int): Int = resources.getDimension(dimen).toInt()
    
    fun Context.dp(@DimenRes dimen: Int): Float = px(dimen) / resources.displayMetrics.density
    

    If you want to handle it without context, you can use Resources.getSystem():

    val Int.dp get() = this / Resources.getSystem().displayMetrics.density // Float
    
    val Int.px get() = (this * Resources.getSystem().displayMetrics.density).toInt()
    

    For example, on an xhdpi device, use 24.dp to get 12.0 or 12.px to get 24

    0 讨论(0)
提交回复
热议问题