ImageButton 添加字体 或 button添加icon

当想在ImageButton上面添加字体的时候,发现在只有android:src并没有android:text,我汗!当时就试着自定义一个 ImageButton,在ondraw里面drawText,但发现在src是的位置并没有对齐方式也没有android:gravity属性,再一次 汗。。。

value/attrs.xml

‍<?xml version="1.0" encoding="utf-8"?>
<resources>
 <declare-styleable name="MyView">
  <attr name="text" format="string" />
 </declare-styleable>
</resources>

layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:test="http://schemas.android.com/apk/res/com.android.test"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">

    <com.android.test.ImageTextButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button1"
    android:src="@drawable/dial_num_1_no_vm"
    style="@style/DialPadButton"  
    android:focusable="false"
    test:text="1234567"
    />
    </LinearLayout>

public class ImageTextButton extends ImageButton {
 
 private Paint mPaint;
 private String str;

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

 public ImageTextButton(Context context, AttributeSet attrs) {
  super(context, attrs);
  // TODO Auto-generated constructor stub
  mPaint = new Paint();
  mPaint.setColor(Color.BLUE);
  mPaint.setTextSize(18);
  TypedArray a = context
    .obtainStyledAttributes(attrs, R.styleable.MyView);
  str = a.getString(R.styleable.MyView_text);
  a.recycle();
 }

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

 @Override
 protected void onDraw(Canvas canvas) {
  // TODO Auto-generated method stub
  super.onDraw(canvas);
  canvas.drawText(str, 60, 40, mPaint);
 }

}

后来突然发现这个可以用Button做到,Button中是可以添加icon,用android:drawableLeft,icon可以用top,left等设置显示位置,drawableleft也可以是selector的xml

<Button android:text="test"  android:id="@+id/test1" 

                android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:drawableLeft="@drawable/dial_num_1_no_vm"
                android:background="@drawable/call_btn_hold"></Button>

导航