问题
I am creating 8 TextView
s 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 TextView
s 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