Android进阶之——自定义view(一)

前言

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的大小和位置等等。

自定义view对于一个android开发者来说是个难点,个人理解比较浅显,欢迎大家讨论,共同进步!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,050评论 25 707
  • 内容抽屉菜单ListViewWebViewSwitchButton按钮点赞按钮进度条TabLayout图标下拉刷新...
    皇小弟阅读 46,658评论 22 664
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,945评论 4 60
  • 通常作为基类,派生其他类。每个想要在ns-3类型和属性系统中集成的类都应该从这个基类派生。 这个基类提供: 公共方...
    shawn168阅读 841评论 0 0
  • 昨天看房 早上看见一群大妈在跳广场舞 那一瞬间相信 这就是幸福 晚上在地铁上 看见一个大妈带着小孩跪着乞讨 心生怜...
    角落蜷缩阅读 137评论 0 0