自定义Android xml属性

本文介绍如何在Android中自定义XML属性来丰富自定义控件的功能。通过定义样式和属性,可以方便地设置控件的外观和行为。文章详细展示了如何创建自定义属性,并在自定义控件和布局文件中使用它们。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        我们都会自定义控件,然后在xml文件当中调用、进行布局。然而系统给定的xml属性往往不能满足我们的要求,因此我们需要自定义属性。例如我们需要为我们的自定义控件MyView自定义一个显示文字的属性。那么,我们需要在values/attrs.xml进行如下编辑:

<resources>
    <declare-styleable name="MyView">
        <attr name="myText" format="string" />
        <attr name="myTextcolor" format="reference|color" />
    </declare-styleable>
</resources>

       其中styleable name一般取跟自定义控件一样的名字。我定义了两个xml属性:第一个是myText,因为format是string,所以调用该属性的时候,相应内容填字符串;第二个是myTextcolor,同理调用该xml属性的时候,相应的内容得是应用资源或者颜色值。

      format 参考:reference:参考某一资源ID;color:颜色值;boolean:布尔值; dimension:尺寸值;float:浮点值;integer:整型值;string:字符串;fraction:百分数; enum:枚举值。

      自定义控件MyView的类中将自定义xml属性值提取出来,分别赋值给textContext和textColor,然后将textContext作为画笔要画的内容,而textColor作为画笔颜色。代码给出:

public class MyView extends View {
    String textContext;
    Paint mTextPaint;
    int textColor;
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.MyView);
        textContext=typedArray.getString(R.styleable.MyView_myText);
        textColor=typedArray.getInteger(R.styleable.MyView_myTextcolor,Color.BLUE);
        typedArray.recycle();
//        初始化画笔
        mTextPaint=new Paint();
//        画笔颜色
        mTextPaint.setColor(textColor);
//        画笔画出来的文字大小
        mTextPaint.setTextSize(34);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(textContext, 0,0, mTextPaint);
    }
}
       xml布局文件如下,自定义控件调用了之前说的两个自定义xml属性:

<LinearLayout 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"
    android:orientation="vertical">

    <com.example.ies171226.hunatest.MyView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:myText="helloworld"
        app:myTextcolor="@color/colorAccent" />
</LinearLayout>
注意要加上命名空间:xmlns:app="http://schemas.android.com/apk/res-auto"com.example.ies171226.hunatest是MyView所在包的包名。程序运行结果是一行红色字体:helloword。









                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值