繁体   English   中英

如何以编程方式为所有TextView设置文本颜色?

[英]How to set text color for all the TextViews programatically?

我正在动态创建8个TextView并将其添加到布局中。 我想设置他们的文字颜色。 因此,我在color.xml中声明了颜色代码,并将其设置为:

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

但是我必须为所有TextView单独进行此操作。 有没有一种方法可以为所有TextView全局设置。 例如,类似于我们在jQuery中可以执行的操作:

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

您可以为此使用Custom TextView

如此处所示:

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

您的自定义类MyTextView将类似于:

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. 
    }
}

希望能帮助到你。

您需要为此创建自定义文本视图,然后在各处使用该文本视图的实例。

范例-

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);
    }

}

您可以在XML文件中定义TextView ,如下所示;

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

然后膨胀这个布局,您需要在类似的代码中实例化TextView

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM