android 自定义view 属性参数值 高效获取

见注释部分和不注释部分,
注释部分,在for循环中,很效率低;


    private int tvwLenght;
    private String edtHint;
    private int tvwColor;
    private String tvwStr;


    TypedArray array=context.obtainStyledAttributes(attrs,R.styleable.MyTvwEdt);
        tvwStr = array.getString(R.styleable.MyTvwEdt_mte_text);
        tvwColor = array.getColor(R.styleable.TwoTextopen_ttopen_textColor, Color.BLACK);
        tvwLenght=array.getInteger(R.styleable.MyTvwEdt_mte_lenght,20);
        edtHint = array.getString(R.styleable.MyTvwEdt_mte_hint);
        array.recycle();//属性获取完之后及时回收
//        int count = attrs.getAttributeCount();
//        for (int i = 0; i < count; i++) {
//            String attrName = attrs.getAttributeName(i);//获取属性名称
//            //根据属性获取资源ID
//            switch (attrName) {
//                //显示的文字
//                case "mte_text":
//                    textId = attrs.getAttributeResourceValue(i, 0);
//                    break;
//                //显示的文字的颜色
//                case "mte_textColor":
//                    textColorId = attrs.getAttributeResourceValue(i, 0);
//                    break;
//                //输入的字符长度
//                case "mte_lenght":
//                    tvwLenght = attrs.getAttributeResourceValue(i, 0);
//                    break;
//                case "mte_hint":
//                    hintId = attrs.getAttributeResourceValue(i, 0);
//                    break;
//
//            }
//        }

attr文件里的样例:

 <declare-styleable name="MyTvwEdt">
        <attr name="mte_text" format="reference" />
        <attr name="mte_textColor" format="reference|color" />
        <attr name="mte_lenght" format="integer"/>
        <attr name="mte_hint" format="reference"></attr>
    </declare-styleable>

xml布局中使用:
注意:在布局的顶部加“app”,你自己定义;写啥都行 ;
xmlns:app=”http://schemas.android.com/apk/res-auto”

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

 <!--机井编码-->
            <com.automic.app.view.MyTvwEdt
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:id="@+id/mte_wellstcd"
                app:mte_lenght="17"
                app:mte_hint="@string/wellstcdhint"
                app:mte_text="@string/wellStcd"
                app:mte_textColor="@color/black">

            </com.automic.app.view.MyTvwEdt>

猜你喜欢

转载自blog.csdn.net/u014624241/article/details/79679018