Tuesday, March 30, 2021

jetpack compose - Accessing font 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.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

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

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        val ptSansRegular = Font(
            R.font.pt_sans_regular_400, FontWeight.W400
        )
        val ptSansItalic = Font(
            R.font.pt_sans_italic_400, FontWeight.W400
        )
        val ptSansBold = Font(
            R.font.pt_sans_bold_700, FontWeight.W700
        )
        val ptSansBoldItalic = Font(
            R.font.pt_sans_bold_italic_700, FontWeight.W700
        )

        Column(
            modifier = Modifier
                .background(Color(0xFFFAD6A5))
                .fillMaxSize()
                .padding(32.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Text(
                text = "Custom font regular",
                fontSize = 30.sp,
                color = Color(0xFF8A3324),
                fontFamily = FontFamily(ptSansRegular)
            )

            Text(
                text = "Custom font italic",
                fontSize = 30.sp,
                color = Color(0xFF8A3324),
                fontFamily = FontFamily(ptSansItalic)
            )

            Text(
                text = "Custom font bold",
                fontSize = 30.sp,
                color = Color(0xFF8A3324),
                fontFamily = FontFamily(ptSansBold)
            )

            Text(
                text = "Custom font bold italic",
                fontSize = 30.sp,
                color = Color(0xFF8A3324),
                fontFamily = FontFamily(ptSansBoldItalic)
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}