標籤:枚舉 relative system utf-8 get str for idt ima
<?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 + ">>>>>>>>>>>>>>>>"); }
Android自訂XML屬性