1. 首先创建一个新的android application.
2. 创建属性
在res/values/ 下创建一个attr.xml 文件,定义好需要的attributes
3. 创建自定义的View
创建一个View, CustomView 继承自View(根据具体的情况,如果需求和已经存在的widget或者layout相差不大,就继承,重写一些方法)
package com.hualu.androidview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class CustomView extends View { private Paint p = null; private String text = null; public CustomView(Context context) { super(context); initCustomView() ; } public CustomView(Context context, AttributeSet attrs){ super(context, attrs ) ; initCustomView() ; TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.custom) ; int indexCount = a.getIndexCount() ; for(int i = 0 ; i < indexCount ; i ++){ int index = a.getIndex(i) ; switch (index) { case R.styleable.custom_text: text = a.getString(index) ; break; case R.styleable.custom_size: p.setTextSize(a.getInt(index, 0)); break; case R.styleable.custom_color: p.setColor(a.getColor(index, 0xFF000000)) ; break; } } a.recycle() ; } void initCustomView(){ p = new Paint(); p.setAntiAlias(true); } ; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawText(text, 10, 10, p) ; } }4. 在layout的文件使用自定义的view
下一篇:优化查询语句的建议具体是什么