android 自訂屬性步驟,android自訂步驟

來源:互聯網
上載者:User

android 自訂屬性步驟,android自訂步驟

一個程式能否吸引使用者,漂亮的UI和優秀的互動是至關重要的因素。因此現在大多數應用不滿足了系統提供好的UI組件,而使用自訂群組件來達到更好的顯示效果。使用自訂群組件大多數情況又會使用自訂屬性。本文記錄了自訂屬性的幾個步驟:

1.規劃好自已需要定義的屬性名稱字及類型

2.在res/values目錄下建立一個attrs.xml; 將之前規劃好的屬性定義在attrs.xml中。具體如下:

1 <declare-styleable name="MyTextView">2     <attr name="textColor" format="color"/>3     <attr name="textSize" format="dimension"/>4     <attr name="text" format="string"/>5     <attr name="background" format="reference|color"/>6 </declare-styleable>

3.屬性定義好了,需要在自訂View中,主要是構造方法中擷取自訂的屬性的值 ,以供我們實現自訂view的需要。自訂屬性使用R.styleable引用,擷取裡面的屬性需要使用“名字_屬性”的方式。TypeArray在使用完成後要進行recycle().如下所示:

 1 public MyTextView(Context context, AttributeSet attrs) { 2         super(context, attrs); 3         mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); 4         TypedArray typeArray = context 5                 .obtainStyledAttributes(attrs, R.styleable.MyTextView); 6  7         mTextColor = typeArray.getColor(R.styleable.MyTextView_textColor, Color.BLACK); 8         mTextSize = typeArray.getDimension(R.styleable.MyTextView_textSize, 14); 9         mText = typeArray.getString(R.styleable.MyTextView_text);10         11         mTextBackground = typeArray.getColor(R.styleable.MyTextView_background, Color.WHITE);12         13         mTextPaint.setColor(mTextColor);14         mTextPaint.setTextSize(mTextSize);15         mTextPaint.setTypeface(Typeface.DEFAULT);16         17         typeArray.recycle();18     }

4.實現好自訂view,然後就是使用自訂view,在xml中設定我們定義的自訂的view的值。如下所示:

 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     xmlns:mytextview = "http://schemas.android.com/apk/res/com.example.viewdemo" 4     android:layout_width="match_parent" 5     android:layout_height="match_parent" 6     android:orientation="vertical" > 7      8     <com.example.view.textview.MyTextView  9         android:layout_width="500dp"10         android:layout_height="wrap_content"11         mytextview:text="my name is text view , i am a text view"12         mytextview:textSize="20sp"13         mytextview:textColor="#000000"14         mytextview:background="#ffffff"15         />16 17 </LinearLayout>

需格外注意上在標紅的語句。要設定xmlns來引用我們上面定義的自訂屬性,命名空間為“mytextview”值為“http://schemas.android.com/apk/res/”+包名“com.example.viewdemo”。然後下面自訂view的tag裡面使用命名空間:屬性名稱的方式對自訂的屬性進行賦值。

如此,我們的自訂屬性即完成,便可以在自訂view中擷取屬性值,進行使用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.