自定义控件的3中方式:
1.组合现有android默认提供的控件:继承ViewGroup或其子类Layout等布局类进行组合
2.调整现有android默认提供的控件:继承View的子类具体类(一般要改那个组件,就继承那个控件)
2创建MyView类继承View
3activity的布局文件中引用
activity_main.xml
app:textColor="#ff0000"
app:textSize="10dp"
app:text="我是翟浩浩"
源码下载:
1.组合现有android默认提供的控件:继承ViewGroup或其子类Layout等布局类进行组合
2.调整现有android默认提供的控件:继承View的子类具体类(一般要改那个组件,就继承那个控件)
3.完全自定义控件:继承View类,里面界面及事件完全有自己控制
1创建attrs.xml
在res----values-----attrs.xml
<span style="font-size:18px;"> <?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="textColor" format="color"></attr>
<attr name="textSize" format="dimension"></attr>
<attr name="text" format="string"></attr>
</declare-styleable>
</resources>
</span>
2创建MyView类继承View
<span style="font-size:18px;">public class MyView extends View {
private int textColor;
private float textSize;
private String text;
private Paint paint;//画笔
// 一般会重写3个构造方法
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint=new Paint();
// 拿到values----attrs中自己定义的值
TypedArray myarray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
// 相对应的设置默认值
textColor=myarray.getColor(R.styleable.MyView_textColor,0xFFFFF);
textSize=myarray.getDimension(R.styleable.MyView_textSize, 30);
text=myarray.getString(R.styleable.MyView_text);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
*视图的绘制事件
* 自动调用
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(textColor);
paint.setTextSize(textSize);
// 画布
// 显示的字是x轴10,y轴10,paint画笔
canvas.drawText(text,10,10,paint);
}
}</span>
3activity的布局文件中引用
activity_main.xml
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<android.zhh.com.myself.MyView
android:layout_width="match_parent"
android:layout_height="50dp"
app:textColor="#ff0000"
app:textSize="10dp"
app:text="我是翟浩浩"
android:layout_marginTop="50dp"
/>
</RelativeLayout></span>
app:textColor="#ff0000"
app:textSize="10dp"
app:text="我是翟浩浩"
源码下载:
MyApp-----myself
http://download.csdn.net/detail/zhaihaohao1/9479103