Android自定义属性以及组合View

概念

自定义组合View是指android给我们提供的View本身功能不够用,但是可以把几个View粘合起来形成一个独立的类,对外部提供统一的职能,内部View之间的逻辑实现可以隐藏,使之整体看起来就像是一个新的View。另外,还可以通过自定义属性功能,使得我们的组合View直接在XML布局文件中方便的使用

实现

定义一个基类,之后的组合View都继承自它

public abstract class BaseCustomView extends RelativeLayout {
    /**
     * 自定义view属性命名空间
     */
    private static final String NAMESPACE = "http://schemas.android.com/apk/res-auto";

    //重载构造函数 通过new构建对象时会调用此处
    //View.java中原文:Simple constructor to use when creating a view from code
    public BaseCustomView(Context context) {
        super(context);
        initView();
    }

    //在XML中构建时会调用此处,也是我们自定义属性的构造函数,style默认用app的主题
    //View.java中原文:Constructor that is called when inflating a view from XML
    //...This version uses a default style of 0, so the only attribute values 
    //applie are those in the Context's Theme and the given AttributeSet
    public BaseCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, getStyleable());
        initAttributes(a);
        initView();
        a.recycle();
    }

    public BaseCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    /**
     * 初始化布局
     */
    private void initView() {
        View view = View.inflate(getContext(), getLayout(), this);
        ButterKnife.bind(this, view);
        initData(view);
    }

    //返回 R.styleable.xxx styleable是自定义的一组declare-styleable
    protected abstract int[] getStyleable();

    //根据获取到的属性数组在代码中初始化属性值
    protected abstract void initAttributes(TypedArray a);

    //获取自定义组合View的布局 R.layout.xxx
    protected abstract int getLayout();

    //初始化一些默认数据
    protected abstract 
  • 一个简单的例子

一般我们在应用中会有很多类似的View,比如设置界面的View都可以抽取出来独立成章,简化代码方便维护下边是一个简单的例子,实现了一个比较通用的设置条目,XML中没有设置相关资源的时候就隐藏相应内部View,否之显示出来。一个空的效果显示如下:

示例
public class SettingItemView extends BaseCustomView {
    private String mLeftString;
    private String mEndString;
    private Drawable mLeftImage;
    private Drawable mEndImage;
    private int mLeftColor;

    public SettingItemView(Context context) {
        super(context);
    }

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

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

    @Override
    protected int[] getStyleable() {
        return R.styleable.SettingItemView;
    }

    @Override
    protected void initAttributes(TypedArray a) {
        mLeftString = a.getString(R.styleable.SettingItemView_textLeft);
        mEndString = a.getString(R.styleable.SettingItemView_textEnd);
        mLeftImage = a.getDrawable(R.styleable.SettingItemView_imageLeft);
        mEndImage = a.getDrawable(R.styleable.SettingItemView_imageEnd);
        mLeftColor = a.getColor(R.styleable.SettingItemView_colorLeft, getResources().getColor(R
                .color.text_color));
    }

    @Override
    protected int getLayout() {
        return R.layout.ui_setting_item;
    }

    @Override
    protected void initData(View view) {
        setLeftText(mLeftString);
        setEndText(mEndString);
        setLeftImage(mLeftImage);
        setEndImage(mEndImage);
        tv_left.setTextColor(mLeftColor);
    }

    public void setLeftImage(Drawable image) {
        iv_left.setImageDrawable(image);
    }

    /**
     * 当没有设置图片资源时隐藏之
     *
     * @param image
     */
    public void setEndImage(Drawable image) {
        if (image != null) {
            iv_end.setVisibility(VISIBLE);
            iv_end.setImageDrawable(image);
        }
    }

    public void setLeftText(String text) {
        tv_left.setText(text);
    }

    /**
     * 当没有设置文字时隐藏之
     *
     * @param text
     */
    public void setEndText(String text) {
        if (!TextUtils.isEmpty(text)) {
            tv_end.setVisibility(VISIBLE);
            tv_end.setText(text);
        } 
    }
}
  • 新建一个属性文件attrs.xml
    添加以下自定义属性(一些通用的可以抽取出来供其它使用):
<!--common-->
    <attr name="textLeft" format="string"/>
    <attr name="textEnd" format="string"/>
    <attr name="imageLeft" format="reference"/>
    <attr name="imageEnd" format="reference"/>

<!--SettingItemView-->
<declare-styleable name="SettingItemView">
    <attr name="textLeft"/>
    <attr name="textEnd"/>
    <attr name="imageLeft"/>
    <attr name="imageEnd"/>
    <attr name="colorLeft" format="color"/>
</declare-styleable>

关于styleable属性类型可以搜索一下有很多资料,就不展开说了
布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/rl_root"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/item_height">

    <View
        android:id="@+id/line"
        android:layout_width="match_parent"
        android:layout_height="0.1dp"
        android:background="#ffd2d2d2"
        android:layout_alignParentBottom="true"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/item_height"
        android:orientation="horizontal"
        android:layout_above="@id/line">

        <ImageView
            android:id="@+id/iv_left"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:scaleType="centerInside"
            android:visibility="gone"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:layout_weight="1"
            android:visibility="gone"/>

        <ImageView
            android:id="@+id/iv_end"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:scaleType="centerInside"
            android:visibility="gone"/>

        <TextView
            android:id="@+id/tv_end"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:visibility="gone"/>

    </LinearLayout>
</RelativeLayout>
  • 应用
    在布局中应用刚才写的组合View就像普通View一样就好了,别忘了在跟布局中添加一行
 xmlns:item="http://schemas.android.com/apk/res-auto"

这样新属性就可以以item的命名空间调用了

<所在包名.SettingItemView
android:id="@+id/siv_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
item:imageLeft="@drawable/xxx"
item:textLeft="test"/>

迁移自CSDN
2015年12月12日 11:02:33
http://blog.csdn.net/u013262051/article/details/50273451

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,050评论 25 707
  • 参考文章。http://blog.csdn.net/xmxkf/article/details/51468648h...
    codeHoward阅读 1,055评论 0 4
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,943评论 4 60
  • 本书已经是第9版了,我们知道这意味着什么。曾经让我们惊讶的是在一次会议上,一位年轻的教授说从我们的书中获益,本书的...
    苏语嫣阅读 201评论 0 0
  • 闲扯淡: 其实本人对算法一直怀着万分敬仰的态度,因为在我心里算法一直是那种高级科学研究者玩的东西,后来学了算法后,...
    wintersal阅读 518评论 0 50