如何改变一个TextView的风格在运行时 [英] How to change a TextView's style at runtime

查看:181
本文介绍了如何改变一个TextView的风格在运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android应用程序上,当用户点击一个的TextView ,我想申请一个定义的样式。

I have an android app on which, when the user taps a TextView, I would like to apply a defined style.

我想找到一个 textview.setStyle(),但它不存在。我试过

I thought to find a textview.setStyle() but it doesn't exists. I tried

textview.setTextAppearance();

,但它不工作

but it does not work.

推荐答案

我通过创建一个新的XML文件 RES /价值/ style.xml 如下这样做:

I did this by creating a new XML file res/values/style.xml as follows:

<?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的文件是这样的:

I also have an entries in my "strings.xml" file like this:

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

于是,在我的code我创建了一个ClickListener捕获上的TextView水龙头事件:

Then, in my code I created a ClickListener to trap the tap event on that TextView:

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

要改回去,你会使用这样的:

To change it back, you would use this:

myTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
myTextView.setBackgroundResource(R.color.normalTextViewColor);

这篇关于如何改变一个TextView的风格在运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆