自定义控件(转)

转自:http://www.jb51.net/article/32172.htm

自定义控件在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 :

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中,直接上代码

public class MainActivity extends Activity implements CustomListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_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;
        }
    }

}

自定义控件(转)

时间: 2024-08-08 19:55:59

自定义控件(转)的相关文章

winform 自定义控件的使用

c#的自定义控件还是很方便的,至少相对于c++而言. 1,当然是建立一个windows 窗体空间库,我这里就是用vs 2015 ,工程名MyControl 第二步.在自定义空间窗体内,拖放这样一组空间.我们发送编辑框的内容给父窗体,然后接受父窗体的发送的内容,显示到listbox 中. 这里会看到我使用了委托和事件,其实,刚入门的我,对于c#里的委托和事件 理解的并不深刻.看到很多地方再用.感觉和c++ 的回调很相似.这里就不纠结了, 后面慢慢理解吧.我们通过委托将子窗体的内容发送到主窗体. n

WPF自定义控件与样式(11)-等待/忙/正在加载状态-控件实现

一.前言 申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等,若有不明白的地方可以参考本系列前面的文章,文末附有部分文章链接. 本文主要有三种实现方式: 简单忙碌状态控件BusyBox: Win8/win10效果忙碌状态控件ProgressRing: 弹出异步等待框WaitingBox: 二.简单忙碌状态控件BusyBox 效果图: 通过属性"IsActive"控制控件是否启用,后台C#代码: /// <summary> /

自定义控件和使用的两种基本方法

有时需要一些组合起来的功能性强的控件,为了以后复用简单,还是自己自定义比较方便. 这里以一个自定义的导航栏为例子,在MainActivity里面使用这个控件. 方法一: 设计并编写自定义控件的布局文件,然后在其他布局文件中include. title的布局文件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android

自定义控件学习——防qq侧滑栏

效果 主要步骤: 1. 在xml布局里摆放内容. include    2. 在自定义ViewGroup里, 进行measure测量, layout布局    3. 响应用户的触摸事件    4. int scrollX = (int) (downX - moveX);    5. getScrollX()获取当前滚动到的位置    6. 平滑动画 先看布局 layout_left <?xml version="1.0" encoding="utf-8"?&g

手机卫士11_ 自定义控件_缓存清理_病毒库更新

拷贝安卓源码中的逻辑,可以考虑先创建一个小项目实现以下效果 1,病毒数据库的自动更新(连接网络,然后获取特征码保存到数据库?) ①工程师发现病毒apk,获取到它的特征码发布到服务器上 通过 MD5 或者ASH1获取特征码 ②客户端杀毒软件下载特征码(可能是 JSON串)到本地客户端 (在打开软件的时候还是打开查杀界面的时候?其实都不适合,应该开启一个服务去定期更新数据库,访问病毒更新特征码地址) 定期更新,timer和timertask,一般一个小时更新一次(测试的时候写短一点) 连接服务器:U

自定义控件一般步骤

自定义组合控件的过程 1.自定义一个View 一般来说,继承相对布局,或者线性布局  ViewGroup:   2.实现父类的构造方法.一般来说,需要在构造方法里初始化自定义的布局文件:    3.根据一些需要或者需求,定义一些API方法: ----------------------------------   4.根据需要,自定义控件的属性,可以参照TextView属性: 5.自定义命名空间,例如: 使用eclipse需添加如下命名空间     xmlns:自定义名称=http://sche

iOS 自定义控件

关于UIToolbar,UINavigationController,UINavigationBar,UIBarButtonItem在ios7的使用的简单的介绍,经过搜索资料做了如下的一些汇集 ----------------------------UIBarButtonItem---------------------------- 1:  UIBarButtonItem 隐藏的方式 [self.btnPunctuation setWidth:0]; 2:  UIBarButtonItem 获

Vs自定义控件设计第一例(直线控件的设计)

目录 一. 杨老师是个热情的人 二. 开始喽 三. 还需要些解释什么吗 四. OK了吗 五.最终代码 一.杨老师是个热情的人 我们的项目开源有一段时间了,我一直以为我有一个很不错的胸怀把自己花了很多精力做出来的项目贡献出来了,我以为同学们会很开心,会像“一个饥饿的人看到面包”一样的扑到了我的项目代码上面快乐的研究起来,但是事实上我们的群里面却异常的冷清.我想应该是大家都还在研究代码来不及说话或者是不爱说话吧,直到今天杨老师给我打电话,说了一些情况,似乎是说大家还不太懂数据库等等,我才知道是我错了

Web用户自定义控件

在新建项的时候,选择Web用户控件,可用来自定义自己的控件,做好后,直接拖到页面即可使用自定义控件与WEB交互,需要在 自定义控件里面 写 属性,如: public string CityID { get { return this.DropDownList1.SelectedValue; } set{ this.DropDownList1.SelectedValue = value;} } 在外面调用的时候如下即可: Label1.Text = this.City1.CityID; 自定义样式

自定义控件三部曲视图篇(三)——瀑布流容器WaterFallLayout实现

前言:只要在前行,梦想就不再遥远 系列文章: Android自定义控件三部曲文章索引:http://blog.csdn.net/harvic880925/article/details/50995268 前面两节讲解了有关ViewGroup的onMeasure.onLayout的知识,这节我们深入性地探讨一下,如何实现经常见到的瀑布流容器,本节将实现的效果图如下: 从效果图中可以看出这里要完成的几个功能: 1.图片随机添加 2.在添加图片时,总是将新图片插入到当前最短的列中 3.每个Item后,