酷代码 AI
菜单
全部AI  /  热门  /  AI问答
服务商

在android开发中,如何统一设置多个view的android:textsize和android:textcolor

在Android开发中,如果你想统一设置多个View的android:textSize和android:textColor,你可以使用自定义的ViewGroup。自定义的ViewGroup是一个继承自ViewGroup的类,它可以帮助你管理多个子View。 以下是一个简单的例子: ```java public class CustomTextViewGroup extends ViewGroup { private Paint mPaint; private int mDefaultTextSize; private int mDefaultTextColor; public CustomTextViewGroup(Context context) { super(context); mPaint = new Paint(); mDefaultTextSize = 16; mDefaultTextColor = Color.BLACK; } public CustomTextViewGroup(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(); mDefaultTextSize = 16; mDefaultTextColor = Color.BLACK; TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextViewGroup); mDefaultTextSize = a.getDimensionPixelSize(R.styleable.CustomTextViewGroup_textSize, mDefaultTextSize); mDefaultTextColor = a.getColor(R.styleable.CustomTextViewGroup_textColor, mDefaultTextColor); a.recycle(); } public CustomTextViewGroup(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mPaint = new Paint(); mDefaultTextSize = 16; mDefaultTextColor = Color.BLACK; TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextViewGroup); mDefaultTextSize = a.getDimensionPixelSize(R.styleable.CustomTextViewGroup_textSize, mDefaultTextSize); mDefaultTextColor = a.getColor(R.styleable.CustomTextViewGroup_textColor, mDefaultTextColor); a.recycle(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); child.setTextSize(TypedValue.COMPLEX_UNIT_PX, mDefaultTextSize); child.setTextColor(mDefaultTextColor); } } } ``` 在这个例子中,我们创建了一个名为CustomTextViewGroup的自定义ViewGroup。它有一个Paint对象用于设置文本的颜色和大小,以及默认的文本大小和颜色。 在onLayout方法中,我们遍历所有的子View,将它们的文本大小和颜色设置为我们预设的值。 然后,你可以在你的布局文件中使用这个自定义的ViewGroup,就像使用普通的TextView一样: ```xml <com.example.CustomTextViewGroup android:layout_width="wrap_content" android:layout_height="wrap_content" app:textSize="20sp" app:textColor="@color/colorPrimary" /> ``` 在这个例子中,我们将文本大小设置为20sp,文本颜色设置为主题色(colorPrimary)。 [2023-11-07 22:47:08 | AI问答 | 600点数解答]

相关提问