MyViewという名前で自作Viewを作り、カスタム属性helloを作る方法のメモ。
まず res/values/attrs.xml を作って属性を定義する。
res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="hello" format="string"/>
</declare-styleable>
</resources>
これで、R.styleable.MyViewとR.styleable.MyView_helloというフィールドが自動生成される。
次に、MyViewのコンストラクタでカスタム属性を読むコードを書く。
MyView.java
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.MyView, defStyle, 0);
this.hello = a.getString(R.MyView_hello);
a.recycle();
}
MyViewを使う時は、属性のために名前空間を宣言する。
layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:takumak="http://schemas.android.com/apk/res/[Rクラスのパッケージ名]"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.blogspot.takumakei.lib.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
takumak:hello="hello world"/>
</LinearLayout>
参考にした情報

0 件のコメント:
コメントを投稿