您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在运行时更改TextView的样式

如何在运行时更改TextView的样式

我通过创建一个新的XML文件res/values/style.xml来做到这一点,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>

</resources>

我的“ strings.xml”文件中也有一个条目,如下所示:

<color name="highlightedTextViewColor">#000088</color>
<color name="normalTextViewColor">#000044</color>

然后,在我的代码中,我创建了一个ClickListener来捕获该TextView上的tap事件: 编辑: 自API 23起,不建议使用setTextAppearance

    myTextView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view){
                    //highlight the TextView
                    //myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
    if (Build.VERSION.SDK_INT < 23) {
       myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
    } else {
       myTextView.setTextAppearance(R.style.boldText);
    }
     myTextView.setBackgroundResource(R.color.highlightedTextViewColor);
                }
            });

要改回它,你可以使用以下命令:

if (Build.VERSION.SDK_INT < 23) {
    myTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
} else{
   myTextView.setTextAppearance(R.style.normalText);
}
myTextView.setBackgroundResource(R.color.normalTextViewColor);
其他 2022/1/1 18:14:18 有502人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶