How to set text color for all the TextViews programatically?

ⅰ亾dé卋堺 提交于 2020-02-05 02:55:11

问题


I am creating 8 TextViews dynamically and adding them in my layout. I want to set their text color. So I have declared the color code in my color.xml and I am setting it as:

txt1.setTextColor(getResources().getColor(R.color.off_white));

But I have to redundantly do this for all the TextViews individually. Is there a way wherein I can set it globally for all the TextViews. Something similar to what we can do in jQuery for example:

$('input[type="text"]').css('color','white');

回答1:


You can use Custom TextView for that.

As shown here:

MyTextView mTxt = new MyTextView(getApplicationContext());  //Use MyTextView instead of TextView where you want to apply color
mTxt.setText("Some text");

Your custom class MyTextView would be something like:

public class MyTextView extends TextView{

    public MyTextView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        this.setTextColor(Color.GREEN); //change color as per your need here. 
    }
}

Hope it helps.




回答2:


You may define TextView in XML file like following;

<TextView 
    android:text="My Text View"
    android:textColor="@color/myColor"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

And then inflate this layout, where you need to instantiate TextView in code like;

LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView tv1 = layoutInflater.inflate(R.layout.my_text_view, null);



回答3:


You need to create your custom text view for that and then use instance of that textview everywhere.

Example -

public class MyTextView extends TextView{

    public MyTextView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        setTextColor(R.color.holo_orange_light);
    }

}


来源:https://stackoverflow.com/questions/26500873/how-to-set-text-color-for-all-the-textviews-programatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!