Sunday, March 28, 2021

jetpack compose - Get dimension resource

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        Column(
            modifier = Modifier
                .background(Color(0xFFFADADD))
                .fillMaxSize()
                .padding(dimensionResource(id = R.dimen.defaultPadding)),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = "A dimension value defined in XML",
                fontSize = 33.sp,
                color = Color(0xFFECEBBD),
                modifier = Modifier
                    .background(Color(0xFFE63E62))
                    .padding(dimensionResource(id = R.dimen.textPadding))
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
res/values/dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="defaultPadding">32dp</dimen>
    <dimen name="textPadding">24dp</dimen>
</resources>