繁体   English   中英

具有自定义属性的Android自定义视图

[英]Android Custom View with custom Attributes

我已经制作了自定义视图,我想为它设置一些自定义属性。 我想将另一个视图的id作为属性传递。

自定义视图attrs:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="IdNumber">
        <attr name="firstName" format="integer"/>
        <attr name="lastName" format="integer"/>
        <attr name="address" format="integer"/>
        <attr name="birthDate" format="integer"/>
    </declare-styleable>
</resources>

我使用自定义视图的布局:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/display_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:layout_centerHorizontal="true"
        android:tag="name"
        android:ems="10" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/id_number"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/display_name"/>

    <ge.altasoft.custom_views.IdNumber
        android:id="@+id/custom_id_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/id_number"
        android:paddingLeft="35dip"
        custom:firstName="@id/display_name"/>


</RelativeLayout>

自定义视图类的构造函数,我想获取属性值:

 public IdNumber (Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews();

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IdNumber);
        final int N = a.getIndexCount();
        for(int i = 0; i < N; i++){
            int attr = a.getIndex(i);
            switch(attr){
                case R.styleable.IdNumber_firstName:
                    int firstNameViewID = a.getInteger(attr, -1);
                    break;
            }
        }
        a.recycle();
    }

问题是int firstNameViewID = a.getInteger(attr, -1); 只是0,而不是View的id。

custom:firstName="@id/display_name" <<<这里应该是错误的但我不知道它有什么问题。 当我为自定义属性分配一些整数值时,它可以工作,但它不适用于Id-s。

感谢您在Advance中提供的帮助。

更改你的define <attr name="firstName" format="reference"/>在你的代码中使用int firstNameViewID = a.getResourceId(attr, -1);

希望这有帮助!

使用custom:firstName="@+id/display_name"并在你的样式中将其更改为<attr name="firstName" format="refernce"/>而不是整数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM