借此机会,顺便复习一下自定义控件。
首先要自定义控件,必须在我们style文件里面写如下代码:
<!-- 自定义控件的属性 -->
<declare-styleable name="DrawableTextView">
<attr name="drawableWidth" format="dimension"/>
<attr name="drawableHeight" format="dimension"/>
</declare-styleable>
对于format的详细介绍,可以看看这篇文章:http://www.cnblogs.com/tiantianbyconan/archive/2012/06/06/2538528.html
写完上面的后,就进行自定义控件的编写,这里我们的编写如下:
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* 创建一个大小可变的图片TextView
* Created by dara on 2015/8/25 0025.
*/
public class DrawableTextView extends TextView {
private int drawWidth, drawHeight;
public DrawableTextView(Context context) {
super(context);
}
public DrawableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public DrawableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.DrawableTextView);
drawWidth = ta.getDimensionPixelSize(R.styleable.DrawableTextView_drawableWidth, 30);
drawHeight = ta.getDimensionPixelSize(R.styleable.DrawableTextView_drawableHeight, 30);
ta.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setRound(drawWidth, drawHeight);
}
private void setRound(int width, int height) {
Drawable[] drawables = this.getCompoundDrawables();
for (int i = 0; i < drawables.length; i++) {
if (drawables[i] != null) {
drawables[i].setBounds(0, 0, width, height);
}
}
this.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]);
}
}
代码不难懂,然后就进行我们xml文件中的写入:
<?xml version="1.0" encoding="utf-8"?>
<com.example.widget.DrawableTextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/extract_goback_tv"
android:layout_width="@dimen/tv_width"
android:layout_height="match_parent"
android:drawableLeft="@drawable/fanhui"
android:drawablePadding="0dp"
android:gravity="center"
android:text="@string/go_back"
app:drawableWidth="8dp"
app:drawableHeight="14dp"
android:padding="7dp"
android:textColor="@android:color/white"
android:textSize="@dimen/txt_size_14_sp" />
注意:
1. xmlns:app=http://schemas.android.com/apk/res-auto
2. app:drawableWidth="8dp"
3. app:drawableHeight="14dp"
好了,写完了,不懂直接留言了,不过我觉得留言的人应该没有。