古詩詞大全網 - 成語經典 - android 中怎麽樣自定義attributes

android 中怎麽樣自定義attributes

寫程序中可能需要用到壹些自定義的view控件,這樣就需要增加壹些自定義的屬性。

比如說我要做個股票報價的TextView,漲是紅色,跌是綠色

1。先在values目錄下創建styles.xml

<resources>

<style name=" Widget. MyTextView" parent="android:Widget" >

<item name="positiveColor" >#FFFF0000</item>

<item name="negetiveColor" >#FF00FF00</item>

</style>

</resources>

2。上面的步驟完成後,在values目錄下創建壹個attrs.xml文件,告訴程序妳自定義的item是什麽類型的

<resources>

<declare-styleable name=" MyTextView" >

<attr name=" positiveColor " format="color" />

<attr name=" negetiveColor " format=" color " />

</declare-styleable>

</resources>

3。在layout設計中引用自定義view並加入style

<com.pan.MyTextView

style="@style/ Widget. MyTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

4。activity中讀取

int positiveColor;

int negetiveColor;

public MyTextView(Context context, AttributeSet attrs, int defStyle)

{

super (context, attrs, defStyle);

TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.TestView, defStyle, 0 );

int n = a.getIndexCount();

for (int i = 0 ; i < n; i++)

{

int attr = a.getIndex(i);

switch (attr)

{

case R.styleable.MyTextView_positiveColor:

positiveColor = a.getColor(attr, Color.RED);

break ;

case R.styleable.MyTextView_negetiveColor:

negetiveColor = a.getColor(attr, Color.Green);

break ;

}

}

}