Android TextView设置字体颜色、文字和大小

一、前言:

Android用ContextCompat替换getResources()获取资源; android SDK 升级到 23 之后,getResource.getColor(R.color.color_name) 过时, 可以使用新加入的方法 ContextCompat.getColor(context, R.color.color_name) 。
SDK 升级到 23 之后,Context类已经提供了getColor(int id)等一系列获取资源文件的方法。

二、使用:

1、MainActivity 类

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var  tvTitle = findViewById(R.id.tv_title)
        var  ivPic = findViewById(R.id.iv_pic)

        // ==========设置文字和颜色===========
        //1、设置标题
        tvTitle.text = resources.getText(R.string.title)
        //2、设置颜色过时
        //tvTitle.setTextColor(resources.getColor(R.color.color_FF0000))
        //3、设置颜色最新方法
       // tvTitle.setTextColor(ContextCompat.getColor(this,R.color.color_FF0000))
        //4、扩展的方式设置文字
        tvTitle.textResource = R.string.title
        //5、扩展的方式设置文字颜色
        tvTitle.textColorResource= R.color.color_FF0000
        //6、设置颜色
        tvTitle.setTextColor(Color.parseColor("#FF47A3"));




        // ==========设置文字大小===========
        tvTitle.textSize = resources.getDimension(R.dimen.ui_sp10)
        //扩展的方式设置文字大小
        tvTitle.textSizeResource(10f)


       // ==========设置图片===========
       // ivPic.setImageResource(R.mipmap.vip_prvite_party)
        //扩展的方式设置图片
        // ivPic.srcResource = R.mipmap.vip_prvite_party
        //扩展的方式设置图片
        ivPic.imageResource = R.mipmap.vip_prvite_party

        //扩展的方式获取dp 和SP转化
        var dp1 = dip(10f)
        var sp1 = dimen(R.dimen.ui_dp10)
        Log.d("LUO","-----dp1:$dp1")
        Log.d("LUO","-----sp1:$sp1")
    }
}

2、Kotlin扩展类 TextView、ImageView和Context

1、TextView类:

package com.example.myapplication.utils

import android.util.TypedValue
import android.widget.TextView
import androidx.annotation.ColorInt

var TextView.textResource: Int
    get() = 0
    set(value) = setText(value)

var TextView.textColorResource: Int
    get() = 0
    set(value) = setTextColor(context.color(value))
/**
 * Set text color quickly
 */
fun TextView.textColor(@ColorInt color: Int) = setTextColor(color)

/**
 * Set text size
 */
fun TextView.textSizeResource(value: Float, unit: Int = TypedValue.COMPLEX_UNIT_SP) {
    when (unit) {
        TypedValue.COMPLEX_UNIT_SP -> textSize = value
        else -> setTextSize(unit, value)
    }
}

2、ImageView类:

package com.example.myapplication.utils
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.widget.ImageView

var ImageView.srcResource: Int
    get() = 0
    set(value) = if (value != 0) setImageResource(value) else setImageDrawable(ColorDrawable(Color.TRANSPARENT))

var ImageView.imageResource: Int
    get() = 0
    set(value) {
        srcResource = value
    }

3、Context类:

package com.example.myapplication.utils

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.DisplayMetrics
import android.util.TypedValue
import androidx.annotation.AttrRes
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
/**
 * Get [DisplayMetrics] from [Resources]
 */
val Context.displayMetrics: DisplayMetrics get() = resources.displayMetrics

/**
 * Calculate dimensions in pixel of dip
 */
fun Context.dip(value: Float): Int = dipF(value).toInt()

/**
 * @see [dip]
 */
fun Context.dip(value: Int): Int = dip(value.toFloat())

/**
 * Calculate dimensions in float of dip
 */
fun Context.dipF(value: Float): Float =
        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, displayMetrics)

/**
 * Convert dimensions in pixel from dip
 *
 * @see [Context.dip]
 */
fun Context?.fromDp(dip: Float): Int = this?.dip(dip)
        ?: Resources.getSystem().displayMetrics.let {
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, it).toInt()
        }

/**
 * Convert dimensions in pixel from sp
 */
fun Context?.fromSp(sp: Float): Int =
        (this?.resources ?: Resources.getSystem()).displayMetrics
                .let {
                    TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, it).toInt()
                }

/**
 * Convert dimensions from pixel
 *
 * @param unit support [TypedValue.COMPLEX_UNIT_DIP], [TypedValue.COMPLEX_UNIT_SP], [TypedValue.COMPLEX_UNIT_PT]
 */
fun Context?.fromPix(valuePixel: Float, unit: Int = TypedValue.COMPLEX_UNIT_DIP): Float =
        (this?.resources ?: Resources.getSystem()).displayMetrics
                .let {
                    when (unit) {
                        TypedValue.COMPLEX_UNIT_DIP -> valuePixel.div(it.density)
                        TypedValue.COMPLEX_UNIT_SP -> valuePixel.div(it.scaledDensity)
                        TypedValue.COMPLEX_UNIT_PT -> valuePixel.div(it.xdpi).times(72F)
                        else -> valuePixel
                    }
                }

/**
 * Get color with [ContextCompat]
 */
fun Context.color(@ColorRes res: Int): Int = ContextCompat.getColor(this, res)

/**
 * Get drawable with context directly
 */
fun Context.drawable(@DrawableRes res: Int): Drawable? =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getDrawable(res)
        } else {
            resources.getDrawable(res)
        }

/**
 * Get dimension pixel size in [Int]
 */
fun Context.dimen(@DimenRes res: Int): Int = resources.getDimensionPixelSize(res)

/**
 * Get dimension pixel size in [Float]
 */
fun Context.dimenF(@DimenRes res: Int): Float = resources.getDimension(res)

/**
 * Get [Drawable] with attr-res
 */
fun Context.drawableFromAttr(@AttrRes attrRes: Int): Drawable? = intArrayOf(attrRes)
        .let {
            val typedArray = obtainStyledAttributes(it)
            val drawable = typedArray.getDrawable(0)
            typedArray.recycle()
            drawable
        }

fun Context.asActivity(): Activity? =
        when (this) {
            is Activity -> this
            is ContextWrapper -> baseContext.asActivity()
            else -> null
        }

3、其它需要的xml类

1、dimens.xml



    
    0.5dp
    1dp
    2dp
    3dp
    4dp
    5dp
    6dp
    7dp
    8dp
    1dp
    10dp
    11dp
    12dp
    13dp
    14dp
    15dp
    16dp
    17dp
    18dp
    19dp
    20dp
    21dp
    22dp
    23dp
    24dp
    25dp
    26dp
    27dp
    28dp
    29dp
    30dp
    31dp
    32dp
    33dp
    34dp
    35dp
    36dp
    37dp
    38dp
    39dp
    40dp
    41dp
    42dp
    43dp
    44dp
    45dp
    46dp
    47dp
    48dp
    49dp
    50dp
    51dp
    52dp
    53dp
    54dp
    55dp
    56dp
    57dp
    58dp
    59dp
    60dp
    61dp
    62dp
    64dp
    65dp
    70dp
    75dp
    80dp
    85dp
    90dp
    95dp
    100dp
    104dp
    180dp


    
    1sp
    2sp
    3sp
    4sp
    5sp
    6sp
    7sp
    8sp
    1sp
    10sp
    11sp
    12sp
    13sp
    14sp
    15sp
    16sp
    17sp
    18sp
    19sp
    20sp
    21sp
    22sp
    23sp
    24sp
    25sp
    26sp
    27sp
    28sp


2、colors.xml



 
    #FF0000

你可能感兴趣的:(Android TextView设置字体颜色、文字和大小)