转:Android自定义控件之详细介绍

自定义控件在android中无处不见,自定义控件给了我们很大的方便。比如说,一个视图为imageview ,imagebutton ,textview 等诸多控件的组合,用的地方有很多,我们不可能每次都来写3个的组合,既浪费时间,效率又低。在这种情况下,我们就可以自定义一个view来替换他们,不仅提升了效率并且在xml中运用也是相当的美观。

一、控件自定义属性介绍

以下示例中代码均在values/attrs.xml 中定义,属性均可随意命名。
1、reference:参考某一资源ID。

示例:

<declare-styleable name = "名称">   
<attr name = "background" format = "reference" />   
<attr name = "src" format = "reference" />   
</declare-styleable> 

2、color:颜色值。
示例:

<declare-styleable name = "名称">   
<attr name = "textColor" format = "color" />   
</declare-styleable>

3、boolean:布尔值。

<declare-styleable name = "名称">   
<attr name = "focusable" format = "boolean" />   
</declare-styleable>

4、dimension:尺寸值。

<declare-styleable name = "名称">   
<attr name = "layout_width" format = "dimension" />   
</declare-styleable>

5、float:浮点值。

<declare-styleable name = "名称">   
<attr name = "fromAlpha" format = "float" />   
<attr name = "toAlpha" format = "float" />   
</declare-styleable>

6、 integer:整型值。

<declare-styleable name = "名称">   
<attr name = "frameDuration" format="integer" />   
<attr name = "framesCount" format="integer" />   
</declare-styleable>

7、string:字符串

<declare-styleable name = "名称">   
<attr name = "text" format = "string" />   
</declare-styleable>

8、fraction:百分数。

<declare-styleable name="名称">   
<attr name = "pivotX" format = "fraction" />   
<attr name = "pivotY" format = "fraction" />   
</declare-styleable>

9、enum:枚举值。

<declare-styleable name="名称">   
<attr name="orientation">   
<enum name="horizontal" value="0" />   
<enum name="vertical" value="1" />   
</attr>   
</declare-styleable>

10、flag:位或运算。

<declare-styleable name="名称">   
<attr name="windowSoftInputMode">   
<flag name = "stateUnspecified" value = "0" />   
<flag name = "stateUnchanged" value = "1" />   
<flag name = "stateHidden" value = "2" />   
<flag name = "stateAlwaysHidden" value = "3" />   
</attr>   
</declare-styleable>

11、多类型。

<declare-styleable name = "名称">   
<attr name = "background" format = "reference|color" />   
</declare-styleable>

二、属性的使用以及自定义控件的实现
1、构思控件的组成元素,思考所需自定义的属性。
比如:我要做一个 <带阴影的按钮,按钮正下方有文字说明>(类似9宫格按钮)
新建values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>   
<resources>   
  <declare-styleable name="custom_view">   
    <attr name="custom_id" format="integer" />   
    <attr name="src" format="reference" />   
    <attr name="background" format="reference" />   
    <attr name="text" format="string" />   
    <attr name="textColor" format="color" />   
    <attr name="textSize" format="dimension" />   
  </declare-styleable>   
</resources>

以上,所定义为custom_view,custom_id为按钮id,src为按钮,background为阴影背景,text为按钮说明,textColor为字体颜色,textSize为字体大小。

2、怎么自定义控件呢,怎么使用这些属性呢?话不多说请看代码,CustomView :

package com.nanlus.custom;

import com.nanlus.custom.R;

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.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomView extends FrameLayout implements OnClickListener {
    private CustomListener customListener = null;
    private Drawable mSrc = null, mBackground = null;
    private String mText = "";
    private int mTextColor = 0;
    private float mTextSize = 20;
    private int mCustomId = 0;
    private ImageView mBackgroundView = null;
    private ImageButton mButtonView = null;
    private TextView mTextView = null;
    private LayoutParams mParams = null;

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

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.custom_view);
        mSrc = a.getDrawable(R.styleable.custom_view_src);
        mBackground = a.getDrawable(R.styleable.custom_view_background);
        mText = a.getString(R.styleable.custom_view_text);
        mTextColor = a.getColor(R.styleable.custom_view_textColor,
                Color.WHITE);
        mTextSize = a.getDimension(R.styleable.custom_view_textSize, 20);
        mCustomId = a.getInt(R.styleable.custom_view_custom_id, 0);
        mTextView = new TextView(context);
        mTextView.setTextSize(mTextSize);
        mTextView.setTextColor(mTextColor);
        mTextView.setText(mText);
        mTextView.setGravity(Gravity.CENTER);
        mTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        mButtonView = new ImageButton(context);
        mButtonView.setImageDrawable(mSrc);
        mButtonView.setBackgroundDrawable(null);
        mButtonView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        mButtonView.setOnClickListener(this);
        mBackgroundView = new ImageView(context);
        mBackgroundView.setImageDrawable(mBackground);
        mBackgroundView.setLayoutParams(new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        addView(mBackgroundView);
        addView(mButtonView);
        addView(mTextView);
        this.setOnClickListener(this);
        a.recycle();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mParams = (LayoutParams) mButtonView.getLayoutParams();
        if (mParams != null) {
            mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
            mButtonView.setLayoutParams(mParams);
        }
        mParams = (LayoutParams) mBackgroundView.getLayoutParams();
        if (mParams != null) {
            mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
            mBackgroundView.setLayoutParams(mParams);
        }
        mParams = (LayoutParams) mTextView.getLayoutParams();
        if (mParams != null) {
            mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
            mTextView.setLayoutParams(mParams);
        }
    }

    public void setCustomListener(CustomListener l) {
        customListener = l;
    }

    @Override
    public void onClick(View v) {
        if (customListener != null) {
            customListener.onCuscomClick(v, mCustomId);
        }
    }

    public interface CustomListener {
        void onCuscomClick(View v, int custom_id);
    }
}

代码很简单,就不多说,下面来看看我们的CustomView是怎么用的,请看:

3、自定义控件的使用
话不多说,请看代码,main.xml:

<?xml version="1.0" encoding="utf-8"?>   
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"   
    xmlns:nanlus="http://schemas.android.com/apk/res/com.nanlus.custom"   
    android:layout_width="fill_parent"   
    android:layout_height="fill_parent" >   
    <LinearLayout   
        android:layout_width="wrap_content"   
        android:layout_height="wrap_content"   
        android:layout_centerHorizontal="true"   
        android:layout_centerVertical="true"   
        android:orientation="horizontal" >   
        <com.nanlus.custom.CustomView   
            android:id="@+id/custom1"   
            android:layout_width="wrap_content"   
            android:layout_height="wrap_content"   
            android:layout_weight="1"   
            nanlus:background="@drawable/background"   
            nanlus:custom_id="1"   
            nanlus:src="@drawable/style_button"   
            nanlus:text="按钮1" >   
        </com.nanlus.custom.CustomView>   
    </LinearLayout>   
</RelativeLayout>

在这里需要解释一下,
xmlns:nanlus="http://schemas.android.com/apk/res/com.nanlus.custom"
nanlus为在xml中的前缀,com.nanlus.custom为包名

4、在Activity中,直接上代码

package com.nanlus.custom;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nanlus.BaseActivity;
import com.nanlus.custom.R;
import com.nanlus.custom.CustomView.CustomListener;

import static com.umeng.analytics.b.g.R;

public class CustomActivity extends BaseActivity implements CustomListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((CustomView) this.findViewById(R.id.custom1)).setCustomListener(this);
    }

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

推荐阅读更多精彩内容