Android自定义控件

来源:互联网 发布:云计算工程师发展前景 编辑:程序博客网 时间:2024/06/01 10:48

在自定义View时,通常会重写onDraw()绘制View的显示内容。如果该View还需要wrap_content属性,还必须重写onMeasure()方法。通过自定义attrs属性,还可以设置新的属性配置值。

在View中有一些比较重要的回调方法:

    onFinishInflate():从XML中加载组件后回调。

    onSizeChanged():组件大小改变时回调。

    onMeasure():回调该方法进行测量。

    onLayout():回调该方法来确定显示的位置。

    onTouchEvent():监听到触摸事件时回调。

自定义View有三种方法:

1、对现有控件进行扩展

2、通过组合来实现新的控件

3、重写View实现全新控件


一、对现有控件进行扩展:

基本就是在onDraw()中对原有控件进行扩展,要扩展哪个控件,就继承哪个控件,比如要扩展TextView,那么久继承TextView。

简单扩展TextView(给TextView添加两层背景):

package com.mfc.myview;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.support.annotation.Nullable;import android.util.AttributeSet;import android.widget.TextView;/** * Created by Administrator on 2017/8/8. * 自定义一个简单的TextView控件 */public class MyTextView1 extends TextView {    private Paint paint;    public MyTextView1(Context context) {        super(context);        initView();    }    public MyTextView1(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);        initView();    }    public MyTextView1(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        initView();    }    private void initView() {        paint = new Paint();    }    @Override    protected void onDraw(Canvas canvas) {        paint.setStyle(Paint.Style.FILL);        paint.setColor(Color.YELLOW);        canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),paint);        paint.setColor(Color.RED);        canvas.drawRect(10,10,getMeasuredWidth()-10,getMeasuredHeight()-10,paint);        //在调用父类方法前,实现自己的逻辑,对TextView来说就是在绘制文本内容前       super.onDraw(canvas);                //在调用父类方法后,实现自己的逻辑,对TextView来说就是在绘制文本内容后 }}

实现文字闪动效果:

package com.mfc.myview;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.LinearGradient;import android.graphics.Matrix;import android.graphics.Paint;import android.graphics.Shader;import android.support.annotation.Nullable;import android.util.AttributeSet;import android.widget.TextView;/** * Created by Administrator on 2017/8/8. * 自定义一个具有闪动效果的TextView */public class MyTextView2 extends TextView {    private int mViewWidth = 0;    private int mViewHeight = 0;    private Paint paint;    private LinearGradient linearGradient;    private Matrix matrix;    private int translate;    public MyTextView2(Context context) {        super(context);    }    public MyTextView2(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);    }    public MyTextView2(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {        super.onSizeChanged(w, h, oldw, oldh);        if (mViewWidth == 0) {            mViewWidth = getMeasuredWidth();            if (mViewWidth > 0) {                paint = getPaint();                linearGradient = new LinearGradient(0, 0, mViewWidth, 0, new int[]{Color.BLUE, Color.WHITE, Color.BLUE}, null, Shader.TileMode.CLAMP);                paint.setShader(linearGradient);                matrix = new Matrix();            }        }    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        /*        * 这里由于View是刷新重绘界面,所以产生了动态的效果        * */        if (matrix != null) {            translate += mViewWidth / 5;            if (translate > 2 * mViewWidth) {                translate = -mViewWidth;            }            matrix.setTranslate(translate, 0);            linearGradient.setLocalMatrix(matrix);            postInvalidateDelayed(100);        }    }}

效果图:


二、创建复合控件:

创建复合控件就是将几个原生控件添加或不添加一些样式后组合在一起作为一个控件使用。

这里组合两个button和一个textview

attrs.xml(指定属性):

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="TopBar">        <attr name="title" format="string"></attr>        <attr name="titleTextSize" format="dimension"></attr>        <attr name="titleTextColor" format="color"></attr>        <attr name="leftTextColor" format="color"></attr>        <attr name="leftBackground" format="reference|color"></attr>        <attr name="leftText" format="string"></attr>        <attr name="rightTextColor" format="color"></attr>        <attr name="rightBackground" format="reference|color"></attr>        <attr name="rightText" format="string"></attr>    </declare-styleable></resources>

MyViewGroup.java(组合控件):

package com.mfc.myview;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Color;import android.graphics.drawable.Drawable;import android.util.AttributeSet;import android.view.Gravity;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.RelativeLayout;import android.widget.TextView;import com.example.administrator.threemyview.R;/** * Created by Administrator on 2017/8/8. * 自定义一个组合控件 */public class MyViewGroup extends RelativeLayout {    //组合控件属性    private String title;    private float  titleTextSize;    private int titleTextColor;    private String leftText;    private Drawable leftBackground;    private int leftTextColor;    private String rightText;    private Drawable rightBackground;    private int rightTextColor;    private Button leftButton;    private Button rightButton;    private TextView titleView;    // 布局属性,用来控制组件元素在ViewGroup中的位置    private LayoutParams leftParams, titlepParams, rightParams;    // 映射传入的接口对象    private topbarClickListener mListener;    public MyViewGroup(Context context) {        super(context);    }    public MyViewGroup(Context context, AttributeSet attrs) {        super(context, attrs);        setBackgroundColor(Color.YELLOW);        //将在attrs.xml中定义的declare-styleable的所有属性存储到TypedArray中        //这里引用的styleable的TopBar,就是在xml中通过<declare-styleable name="TopBar">指定的name        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);        //从TypedArray中取出对应的值来为要设置的属性赋值        title = ta.getString(R.styleable.TopBar_title);        titleTextSize = ta.getDimension(R.styleable.TopBar_titleTextSize,10);        titleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor,0);        leftText = ta.getString(R.styleable.TopBar_leftText);        leftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);        leftTextColor = ta.getColor(R.styleable.TopBar_leftTextColor,0);        rightText = ta.getString(R.styleable.TopBar_rightText);        rightBackground = ta.getDrawable(R.styleable.TopBar_rightBackground);        rightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor,0);        leftButton = new Button(context);        rightButton = new Button(context);        titleView = new TextView(context);        //为创建的组件元素赋值        //值来源于引用的xml文件中对应的值        leftButton.setText(leftText);        leftButton.setBackground(leftBackground);        leftButton.setTextColor(leftTextColor);        rightButton.setText(rightText);        rightButton.setBackground(rightBackground);        rightButton.setTextColor(rightTextColor);        titleView.setText(title);        titleView.setTextColor(titleTextColor);        titleView.setTextSize(titleTextSize);        titleView.setGravity(Gravity.CENTER);        //为组件元素这只相应的布局元素        leftParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);        leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT,TRUE);        //添加到ViewGroup        addView(leftButton,leftParams);        rightParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);        rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,TRUE);        //添加到ViewGroup        addView(rightButton,rightParams);        titlepParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);        titlepParams.addRule(RelativeLayout.CENTER_IN_PARENT,TRUE);        //添加到ViewGroup        addView(titleView,titlepParams);        // 按钮的点击事件,不需要具体的实现,        // 只需调用接口的方法,回调的时候,会有具体的实现        rightButton.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                mListener.rightClick();            }        });        leftButton.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                mListener.leftClick();            }        });    }    public MyViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    // 暴露一个方法给调用者来注册接口回调    // 通过接口来获得回调者对接口方法的实现    public void setOnTopbarClickListener(topbarClickListener mListener) {        this.mListener = mListener;    }    /**     * 设置按钮的显示与否 通过id区分按钮,flag区分是否显示     */    public void setButtonVisable(int id, boolean flag) {        if (flag) {            if (id == 0) {                leftButton.setVisibility(View.VISIBLE);            } else {                rightButton.setVisibility(View.VISIBLE);            }        } else {            if (id == 0) {                leftButton.setVisibility(View.GONE);            } else {                rightButton.setVisibility(View.GONE);            }        }    }    // 接口对象,实现回调机制,在回调方法中    // 通过映射的接口对象调用接口中的方法    // 而不用去考虑如何实现,具体的实现由调用者去创建    public interface topbarClickListener {        // 左按钮点击事件        void leftClick();        // 右按钮点击事件        void rightClick();    }}

引用Activity:

package com.example.administrator.threemyview;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast;import com.mfc.myview.MyViewGroup;public class SomeViewActivity extends AppCompatActivity {    private MyViewGroup mygroup,mygroup1;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.someview);        mygroup = (MyViewGroup) findViewById(R.id.mygroup);        mygroup1 = (MyViewGroup) findViewById(R.id.mygroup1);        mygroup1.setButtonVisable(0,true);        mygroup1.setButtonVisable(1,false);        mygroup.setOnTopbarClickListener(new MyViewGroup.topbarClickListener() {            @Override            public void leftClick() {                Toast.makeText(SomeViewActivity.this,"点击了左边的按钮",Toast.LENGTH_LONG).show();            }            @Override            public void rightClick() {                Toast.makeText(SomeViewActivity.this,"点击了右边的按钮",Toast.LENGTH_LONG).show();            }        });        mygroup1.setOnTopbarClickListener(new MyViewGroup.topbarClickListener() {            @Override            public void leftClick() {                Toast.makeText(SomeViewActivity.this,"点击了左边的按钮",Toast.LENGTH_LONG).show();            }            @Override            public void rightClick() {                Toast.makeText(SomeViewActivity.this,"点击了右边的按钮",Toast.LENGTH_LONG).show();            }        });    }}

引用xml:注意要添加:xmlns:custom="http://schemas.android.com/apk/res-auto"
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:custom="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <com.mfc.myview.MyViewGroup        android:id="@+id/mygroup"        android:layout_width="match_parent"        android:layout_height="40dp"        custom:title="自定义标题"        custom:titleTextColor="#123412"        custom:titleTextSize="10sp"        custom:leftTextColor="#ffffff"        custom:leftBackground="@drawable/blue_button"        custom:leftText="返回"        custom:rightTextColor="#ffffff"        custom:rightBackground="@drawable/blue_button"        custom:rightText="添加"        />    <com.mfc.myview.MyViewGroup        android:id="@+id/mygroup1"        android:layout_marginTop="20dp"        android:layout_width="match_parent"        android:layout_height="40dp"        custom:title="自定义标题"        custom:titleTextColor="#123412"        custom:titleTextSize="10sp"        custom:leftTextColor="#ffffff"        custom:leftBackground="@drawable/blue_button"        custom:leftText="返回"        /></LinearLayout>

效果图:


三、重写View实现全新控件:

重写View实现全新控件通常需要继承View类,并重写它的onDraw()、onMeasure()等方法来进行绘制,同时重写onTouchEvent()等触控事件来实现交互逻辑。

示例一:弧形展示图:

package com.mfc.myview;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.RectF;import android.support.annotation.Nullable;import android.util.AttributeSet;import android.view.View;/** * Created by Administrator on 2017/8/8. */public class NewView1 extends View {    //获取xml引用中设置的长宽    private int width,height;    //最终绘制时参考长度    private int length;    //定义画笔    private Paint paint;    private float mSweepValue;    private String text = "";    public NewView1(Context context) {        super(context);    }    public NewView1(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);    }    public NewView1(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        //测量获取界面上的长宽        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        width = MeasureSpec.getSize(widthMeasureSpec);        height = MeasureSpec.getSize(heightMeasureSpec);        initView();    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        //绘制内圆        canvas.drawCircle((float) (length / 2), (float) (length / 2) , (float) (length / 4) , paint);        paint.setTextAlign(Paint.Align.CENTER);        paint.setColor(Color.RED);        paint.setTextSize((float) (length / 8));        //绘制文字        canvas.drawText(text,0,text.length(),(float) (length / 2),(float) (length / 2 +length / 32),paint);        //设置圆环大小        RectF rectF = new RectF((float)(length * 0.1),(float)(length * 0.1),(float)(length * 0.9),(float)(length * 0.9));        paint.setStyle(Paint.Style.STROKE);        paint.setStrokeWidth((float)(length * 0.1));        //绘制圆环,(mSweepValue / 100f) * 360f计算圆弧的度数        canvas.drawArc(rectF,0,(mSweepValue / 100f) * 360f,false,paint);    }    private void initView(){        //最终绘制参考长度        length = 0;        //去长宽中较短的那个长度        if(width >= height){            length = height;        }else {            length = width;        }        paint = new Paint();        paint.setStyle(Paint.Style.FILL);        paint.setColor(Color.BLUE);    }    public void setText(String s){        if(s == null||s.equals("")){            text = "";        }else{            text  = s;        }    }    public void setmSweepValue(float sweepValue){        if (sweepValue != 0){            mSweepValue = sweepValue;        }else {            mSweepValue = 25;        }    }}

调用Activity:

protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.newview);        newview1 = (NewView1) findViewById(R.id.newview1);        newview1.setmSweepValue(30);        newview1.setText("30%");    }

效果图:


示例二:音频条形图:

package com.mfc.myview;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.LinearGradient;import android.graphics.Paint;import android.graphics.Shader;import android.support.annotation.Nullable;import android.util.AttributeSet;import android.view.View;/** * Created by Administrator on 2017/8/8. */public class NewViewSound extends View {    private int count = 10;    private Paint paint;    private LinearGradient linearGradient;    public NewViewSound(Context context) {        super(context);        paint = new Paint();    }    public NewViewSound(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);        paint = new Paint();    }    public NewViewSound(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        paint = new Paint();    }    @Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {        super.onSizeChanged(w, h, oldw, oldh);        linearGradient = new LinearGradient(0,0,(int)(getWidth()*0.6/count),getHeight(), Color.BLUE,Color.YELLOW, Shader.TileMode.CLAMP);        paint.setShader(linearGradient);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        float left = 0;        float top = 0;        float right = 0;        float bottom = 0;        for (int i = 0; i < count; i++){            left = (float) (getWidth()*0.4/2+30*i+10);            top = (float) (Math.random()*getHeight());            right = (float) (getWidth()*0.4/2+30*(i+1));            bottom = getHeight();            canvas.drawRect(left,top,right,bottom,paint);            postInvalidateDelayed(300);        }    }}

效果图:(这个图是动态的)


源码下载:http://download.csdn.net/detail/fancheng614/9925518

原创粉丝点击