Androidでのカスタム属性TypedArrayの使い方

3273 ワード

Androidの開発では、従来のページレイアウトが私たちのニーズを満たすことができない場合があります.通常はViewをカスタマイズし、構造方法やonDrawなどの関数を書き直し、自分で定義した複雑なviewを具体的に実現する必要があります.
次の手順に従います.
1>プロジェクトファイルres/valueの下にattrを作成します.xmlファイル.このファイルには、いくつかのattrセットが含まれています.たとえば、
  


    
        
        
    
  

ここではルートラベルで、いくつか定義できます.中nameは変数の名前を定義し、次は複数の属性をカスタマイズできます.
場合、その属性の名前は「myTextSize」であり、formatはこの属性タイプがdimensionであることを指定し、フォントのサイズのみを表すことができる.formatは、他のタイプを指定することもできます.例えば、referenceは参照を表し、あるリソースID string表示文字列color表示色値dimension表示寸法値boolean表示ブール値integer表示整数値float表示浮動小数点値fraction表示パーセンテージenum表示列挙値flag表示ビット演算を参照
2>カスタムviewを使用するレイアウトファイルに次の行を入力します.
xmlns:myapp=http://schemas.android.com/apk/res/com.eyu.attrtextdemo緑は自分で定義した属性の接頭辞の名前で、ピンクはプロジェクトのパッケージ名で、これによって、私たちが自分で定義したviewの属性の中で、自分でattrで定義した属性を使用することができます.例えば:


        
        
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            myapp:myTextSize="20sp"
            myapp:myColor="#324243"/>

    

3>カスタムviewのコードにカスタム属性を導入し、コンストラクション関数contextを変更するobtainStyledAttributesメソッドを呼び出すことでTypeArrayを取得し、このTypeArrayによって属性を設定するobtainStyledAttributesメソッドは3つあり、最もよく使われるのはパラメータが1つあるobtainStyledAttributes(int[]attrs)で、そのパラメータは直接styleableで取得される
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);呼び出しが終了したら、必ずrecycle()メソッドを呼び出します.そうしないと、今回の設定は次回の使用に影響します.
public class MyView extends View{
    public Paint paint;

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();

        TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);
        int textColor = a.getColor(R.styleable.MyView_myColor, 003344);
        float textSize = a.getDimension(R.styleable.MyView_myTextSize, 33);
        paint.setTextSize(textSize);
        paint.setColor(textColor);
        a.recycle();
    }

    public MyView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub  
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub  
        super.onDraw(canvas);
        paint.setStyle(Style.FILL);
        canvas.drawText("aaaaaaa", 10, 50, paint);
    }

} 

参考記事:http://blog.csdn.net/eyu8874521/article/details/8552534
                 http://blog.csdn.net/janice0529/article/details/34425549