前言

Android App开发过程中,经常会遇到系统框架中提供的控件无法满足我们产品的设计需求,这时候就必须自定义view了,有时候为了方便,也可以选择自定义view。

在我看来,android自定义view的实现方式可以分成三种:继承控件组合控件自绘控件。其中,最简单的就是继承控件和组合控件。这次分享的便是继承控件和组合控件的实现方式,下篇文章将会介绍自绘控件的实现方式。

继承控件

继承控件不需要我们重新去实现一个控件,只需要去继承一个现有的控件,然后在这个控件的基础上增加一些我们需要的新的功能,对外提供调用的接口,就可以形成一个自定义控件了。这种自定义控件的特点就是不仅能够按照我们的需求加入相应的功能,还可以保留原生控件的所有功能。
比如下面这个自定义view:

package com.eebbk.textplayer;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

import com.eebbk.contentview.R;

/**
 * Created by zhangshao on 2016/7/26.
 */
public class AudioButton extends Button{
    /**
     * 按钮的播放图片资源
     */
    private static final int[] AUDIO_RES_DRAWABLE_IDS = new int[] {
            R.drawable.ptr_audio_btn_0,R.drawable.ptr_audio_btn_1,R.drawable.ptr_audio_btn_2
    };
    public AudioButton(Context context) {
        super(context);
    }

    public AudioButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AudioButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 开始动画
     */
    public void startAudioAnim(){
        stopAudioAnim();

        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(this, "Anim", 0, AUDIO_RES_DRAWABLE_IDS.length-1);
        objectAnimator.setDuration(300);
        objectAnimator.setRepeatCount(-1);
        objectAnimator.start();
        this.setTag(objectAnimator);
    }

    /**
     * 结束动画
     */
    public void stopAudioAnim(){
        ObjectAnimator objectAnimator = (ObjectAnimator) this.getTag();
        if(objectAnimator != null){
            objectAnimator.cancel();
        }
    }

    public void setAnim(int position){
        if(position < 0 || position >= AUDIO_RES_DRAWABLE_IDS.length){
            return;
        }
        this.setBackgroundResource(AUDIO_RES_DRAWABLE_IDS[position]);
    }
}

使用方法同Button一样,可以使用:

AudioButton audioBtn = new AudioButton(this);
//其他button的配置

也可以在布局里使用,如:

<com.eebbk.textplayer.AudioButton
            android:id="@+id/audio_button_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

在需要开始播放动画的地方调用:audioBtn.startAudioAnim();
在需要结束播放动画的地方调用:audioBtn.stopAudioAnim();

AudioButton 继承Button,在原有Button的基础上,增加按钮播放动画和结束动画,使得AudioButton既可以使用Button的setText()之类原有的方法,也可以使用新增的startAudioAnim()和stopAudioAnim()方法。
万变不离其宗,TextView、ImageView…等等view都可以继承,甚至RelativeLayout等ViewGroup也可以继承,实现最简单的自定义view。

组合控件

组合控件的用法和继承控件的用法差不多。定义一个类,继承LinearLayout或者RelativeLayout等其他ViewGroup,然后增加我们想要的功能。
举个例子,这里我就不贴完整代码了,如ExpandView:

布局文件layout_english_point_read_expand_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv_expand_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/english_bg_expand_no_arrow"
        android:clickable="false"
        android:gravity="left|top"
        android:lineSpacingExtra="@dimen/english_point_read_expand_textview_lineSpacingExtra"
        android:textColor="@color/black"
        android:textSize="15sp" />

    <RelativeLayout
        android:id="@+id/iv_show_head_icon_layout_id"
        android:layout_width="@dimen/point_read_show_head_icon_width"
        android:layout_height="@dimen/point_read_show_head_icon_height"
        android:background="@drawable/english_bg_show_head_icon_user"
        android:contentDescription="@null"
        android:visibility="invisible" >

        <com.eebbk.englishpointread.expandview.CircleImageView
            android:id="@+id/iv_show_head_icon_user_id"
            android:layout_width="@dimen/point_read_show_head_icon_user_width"
            android:layout_height="@dimen/point_read_show_head_icon_user_height"
            android:layout_marginLeft="@dimen/point_read_show_head_icon_padding_left"
            android:layout_marginTop="@dimen/point_read_show_head_icon_padding_top"
            android:contentDescription="@null"
            android:src="@drawable/english_bg_show_head_icon_empty"
            app:border_color="#ffffff"
            app:border_width="0dp" />
    </RelativeLayout>

    <ImageView
        android:id="@+id/finger_id"
        android:layout_width="@dimen/english_point_read_finger_width"
        android:layout_height="@dimen/english_point_read_finger_height"
        android:background="@drawable/expand_txt_long_press_finger_anim"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/drag_id"
        android:layout_width="@dimen/english_point_read_drag_width"
        android:layout_height="@dimen/english_point_read_drag_height"
        android:background="@drawable/english_point_read_drag_selector"
        android:visibility="visible" />

</FrameLayout>

ExpandView 的实现:

public class ExpandView extends FrameLayout {

    public static final String CLICK_SHOW_GUIDE = "click_show_guide";
    public static final String NORMAL = "normal";
    private Context mContext = null;
    private View mRootView = null;
    private TextView mExpandContentTv = null;
    private RelativeLayout mShowHeadIconLayout = null;
    private CircleImageView mShowHeadIconIv = null;

    private ImageView mFingerIv = null;
    private ImageView mDragIv = null;

    private int orderOfClick;
    private int pageIndex;
    private String chin;
    private String eng;
    private boolean isExpand = false;

    private ExpandTextClickListener mExpandTextClickListener = null;

    private ExplainListener mExplainListener = null;

    public ExpandView(Context context) {
        super(context);
        mContext = context;
        initView();
    }

    public ExpandView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initView();
    }

    public void setIsExpand(boolean isExpand) {
        this.isExpand = isExpand;
    }

    @SuppressWarnings("deprecation")
    private void initView() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        mRootView = inflater.inflate(R.layout.layout_english_point_read_expand_view, this);

        mExpandContentTv = (TextView) mRootView.findViewById(R.id.tv_expand_id);
        mShowHeadIconLayout = (RelativeLayout) mRootView.findViewById(R.id.iv_show_head_icon_layout_id);
        mShowHeadIconIv = (CircleImageView) mRootView.findViewById(R.id.iv_show_head_icon_user_id);
        mFingerIv = (ImageView) mRootView.findViewById(R.id.finger_id);
        mDragIv = (ImageView) mRootView.findViewById(R.id.drag_id);

    }

    public void expandText(ClickAreaType mClickAreaType, ManagerIntent mMIInfo) {
        //实现放大的操作
    }

    public void showFingerIv(int rId) {
        mFingerIv.setVisibility(View.VISIBLE);
        mFingerIv.setBackgroundResource(rId);
        AnimationDrawable animDrawable = (AnimationDrawable) mFingerIv.getBackground();
        if (animDrawable != null) {
            animDrawable.start();
        }
    }

    public void hideFinger() {
        AnimationDrawable animDrawable = (AnimationDrawable) mFingerIv.getBackground();
        if (animDrawable != null) {
            animDrawable.stop();
        }
        mFingerIv.setVisibility(View.GONE);
    }

    public void setExplainListener(ExplainListener explainListener) {
        this.mExplainListener = explainListener;

    /**
     * 有些内部类我没有贴出来,主要是组合控件内,子控件的处理,以及变量的处理
     */
}

ExpandView主要是实现点击放大等。
具体步骤:

  1. 新建一个布局文件xml(你需要的布局);
  2. 新建一个类,继承布局文件根节点的ViewGroup,如ExpandView布局文件的根布局节点是FrameLayout,所以ExpandView继承了FrameLayout;
  3. 动态载入布局文件,然后获取布局文件里的子控件,通过布局.findViewById()获取,如ExpandView通过
    mRootView.findViewById(),原理和Activity.findViewById()相同;
  4. 实现子控件的相关方法,如点击事件等;
  5. 增加你所需要的方法;

然后在activity的布局里使用:

<com.eebbk.englishpointread.expandview.ExpandView
        android:id="@+id/expand_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true" />

总结

继承控件和组合控件相比于自绘控件会显得简单点,但是自由度不高。很多时候继承控件,组合控件以及自绘控件都是综合使用,组合控件里的子控件也可以使用继承控件的自定义view。为了更好的自定义view ,继承控件和组合控件会采用自绘控件的实现,如重新绘制view的大小和位置等等。