Android-自定义控件的两种方法

前言:

Android控件可以分为:组合控件和原生控件。

举例:组合控件----像广告条控件就是组合控件:它由:ViewPager和一些布局组合而成。

      原生控件----继承View、ViewGroup 或继承现有的控件

自定义控件的两种方法:

一、1.写一个继承自View的类

       2.在布局文件中引用该自定义控件

               3.在自定义控件中加入自定义属性

<com.lcj.view.ImageAndText 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        Text = "@string/lcj"
        Src = "@drawable/b"/>

       4.在自定义的类中的构造方法中写如下:

public ImageAndText(Context context, AttributeSet attrs) {
super(context, attrs);
//返回对应属性资源的ID
textId = attrs.getAttributeResourceValue(null, "Text", 0);
srcId = attrs.getAttributeResourceValue(null, "Src", 0);
}

5.之后在ondraw中根据textId和srcId获取到具体的资源并画在界面上

二、1.写一个继承自View的类

       2.自定义控件的属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
    </declare-styleable>
</resources>

其中format可以是:reference string color dimension boolean integer float fraction enum flag

               3.在自定义类中的构造方法中获取到布局文件中的数据

public ImageAndText2(Context context, AttributeSet attrs) {
super(context, attrs);
//获取自定义属性的数组
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
//从typeArray数组中获取到自定义的颜色属性---默认是红色
int textColor = typedArray.getColor(R.styleable.MyView_textColor, Color.RED);
//从typeArray数组中获取到自定义的字体大小属性---默认是15
float textSize = typedArray.getDimension(R.styleable.MyView_textSize, 15);
paint = new Paint();
paint.setTextSize(textSize);
paint.setColor(textColor);
//保持以后使用该属性一致性
typedArray.recycle();
}

       4.在onDraw方法中进行绘制。

注意:

  1、如果自定义的view是直接放在layout布局文件中应用的话,则其构造函数中一定有包含Attributes类型参数,否则付出Error inflate……错误

  2、如果是在java代码中直接创建自定义view对象的话则只需有Context类型的参数构造函数即可

  3、AttributeSet中封装了布局文件中控件的属性。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值