zoukankan      html  css  js  c++  java
  • Android自定义XML属性

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <declare-styleable name="RatioLayout">
            <attr name="picRatio" format="float" />
            <attr name="relative">
                <enum name="width" value="0" />
                <enum name="height" value="1" />
            </attr>
        </declare-styleable>
    
    </resources>

    上面分别写了两种典型的XML属性的配置,需要在values-attrs文件中编写。

    第一种就是name,后面直接跟一个类型,这样可以在XML中自己任意配置。

    第二种是枚举,这样就只能选择固定的属性了。

    那么,问题来了,如何在View中对这些属性读取呢??下面介绍两种方法。

    1、

            <com.itheima.googleplay_8.views.RatioLayout
                xmlns:itheima="http://schemas.android.com/apk/res-auto"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                itheima:relative="width"
                itheima:picRatio="2.43" >
        public RatioLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
    
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioLayout);
    
            mPicRatio = typedArray.getFloat(R.styleable.RatioLayout_picRatio, 0);
    
            mRelative = typedArray.getInt(R.styleable.RatioLayout_relative, RELATIVE_WIDTH);
    
            typedArray.recycle();
        }

    2、

        <com.example.myview.MyView
            android:id="@+id/myView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            yueqing:content="内容"
            yueqing:title="标题" >
        </com.example.myview.MyView>
    public MyView(Context context, AttributeSet attrs) {
            super(context, attrs);
    
            View inflate = View.inflate(context, R.layout.myview, null);
            CheckBox cb = (CheckBox) inflate.findViewById(R.id.cb);
            TextView tv = (TextView) inflate.findViewById(R.id.tv);
            String content = attrs.getAttributeValue(
                    "http://schemas.android.com/apk/res/com.example.myview",
                    "content");
            if (!cb.isChecked()) {
                tv.setText(content);
            }
            
            this.addView(inflate);
            int attributeCount = attrs.getAttributeCount();
            System.out.println(attributeCount + ">>>>>>>>>>>>>>>>");
        }
  • 相关阅读:
    报表自动化: 商业智能背后的秘密
    谈谈个人对 TDD (测试驱动开发) 的理解
    初识 Inception
    从软件生命周期看应用安全(网络安全)
    Spring JPA save 实现主键重复抛异常
    QMdiArea及QMdiSubWindow实现父子窗口及布局方法
    QTcpServer实现多客户端连接
    C++设计模式
    QTreeView/QTableView中利用QStandardItem实现复选框三种形态变化
    Qt富文本编辑器QTextDocument
  • 原文地址:https://www.cnblogs.com/tinyclear/p/6100042.html
Copyright © 2011-2022 走看看