Android 使用自定义属性

本文详细介绍了如何在Android开发中自定义属性与自定义View,包括创建属性文件、修改布局文件及获取自定义属性的方法。通过实例演示了如何在自定义属性中添加自定义属性,并在布局文件中引用这些属性来实现特定的UI效果。

有的时候我们需要自定义自己的控件属性(在自定义View中使用)

可以参照官方例子去做


1.,创建自己属性文件,res/values/attrs.xml:

例子如下:

<declare-styleable name="CustomLayoutLP">
    <attr name="android:layout_gravity" />
    <attr name="layout_position">
        <enum name="middle" value="0" />
        <enum name="left" value="1" />
        <enum name="right" value="2" />
    </attr>
</declare-styleable>
这里的CustomlayoutLP为该自定义属性的名称,以后会在代码中用到,

两个<attr>节点为属性节点,在这里添加自己的属性



2.修改布局文件

例子如下:

<com.example.android.apis.view.CustomLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res/com.example.android.apis"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <!-- put first view to left. -->
    <TextView
            android:background="@drawable/filled_box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_position="left"
            android:layout_gravity="fill_vertical|center_horizontal"
            android:text="l1"/>
注意这里的xmlns:app="http://schemas.android.com/apk/res/com.example.android.apis"

这个是你的属性的命名控件,其中app为属性前缀,与平常的"android"类似,com.example.android.apis为你的应用的包名(在manifest文件中可见)

修改这两处过后就可以在你的控件中添加自己的属性值



3.在自定义属性中获取自己的属性值:

例子如下:

 public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);

            // Pull the layout param values from the layout XML during
            // inflation.  This is not needed if you don't care about
            // changing the layout behavior in XML.
            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.CustomLayoutLP);
            gravity = a.getInt(R.styleable.CustomLayoutLP_android_layout_gravity, gravity);
            position = a.getInt(R.styleable.CustomLayoutLP_layout_position, position);
            a.recycle();
        }
前面1中的属性的名称在这里用到,获取属性的格式为: 属性名_属性值名

记得最后recyle一下,可能以后需要重用


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值