Android图文居中显示控件使用方法详解图文居中显示控件使用方法详解
主要为大家详细介绍了Android图文居中显示控件的使用方法,文中示例代码介绍的非常详细,具有一定的参考
价值,感兴趣的小伙伴们可以参考一下
最近项目中用到了文字图标的按钮,需要居中显示,如果用TextView实现的方式,必须同时设置padding和
drawablePadding。如下:
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_xxx"
android:drawablePadding="-60dp"
android:minHeight="48dp"
android:gravity="center"
android:padding="80dp" />
这种方式需要自己做精确计算。比较麻烦。另外还有一种方式就是用线性布局包裹ImageView和TextView,但这样会增加布
局层级。于是自己封装了一个控件DrawableCenterTextView。
attrs.xml文件中定义属性:
<declare-styleable name="DrawableCenterTextView">
<attr name="android:text" />
<attr name="android:textColor" />
<attr name="android:textSize" />
<attr name="android:textStyle" />
<attr name="android:drawablePadding" />
<attr name="android:drawableLeft" />
<attr name="android:drawableTop" />
<attr name="android:drawableRight" />
<attr name="android:drawableBottom" />
</declare-styleable>
对应的Java代码如下:
public class DrawableCenterTextView extends View {
static final int LEFT = 0;
static final int TOP = 1;
static final int RIGHT = 2;
static final int BOTTOM = 3;
private CharSequence mText;
private ColorStateList mTextColor;
private float mTextSize;
private int mTextStyle;
private int mDrawablePadding;
private Drawable[] mCompoundDrawables;
private Rect mTextBounds;
private Rect mDrawableLeftBounds;
private Rect mDrawableTopBounds;
private Rect mDrawableRightBounds;
private Rect mDrawableBottomBounds;
private TextPaint mTextPaint;
public DrawableCenterTextView(Context context) {
this(context, null);
}
public DrawableCenterTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawableCenterTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Drawable drawableLeft = null, drawableTop = null, drawableRight = null, drawableBottom = null;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.DrawableCenterTextView, defStyleAttr, 0);
mText = ta.getText(R.styleable.DrawableCenterTextView_android_text);
mTextColor = ta.getColorStateList(R.styleable.DrawableCenterTextView_android_textColor);
mTextSize = ta.getDimensionPixelSize(R.styleable.DrawableCenterTextView_android_textSize, 15);
mTextStyle = ta.getInt(R.styleable.DrawableCenterTextView_android_textStyle, 0);
drawableLeft = ta.getDrawable(R.styleable.DrawableCenterTextView_android_drawableLeft);
drawableTop = ta.getDrawable(R.styleable.DrawableCenterTextView_android_drawableTop);