詳解Android自訂控制項屬性_Android

來源:互聯網
上載者:User

在Android開發中,往往要用到自訂的控制項來實現我們的需求或效果。在使用自訂
控制項時,難免要用到自訂屬性,那怎麼使用自訂屬性呢?

在檔案res/values/下建立attrs.xml屬性檔案,中定義我們所需要的屬性。

<?xml version="1.0" encoding="utf-8"?><resources><!-- resource是跟標籤,可以在裡面定義若干個declare-styleable -->  <declare-styleable name="custom_view"><!-- name定義了變數的名稱 -->    <attr name="custom_color" format="color"></attr> <!-- 定義對應的屬性,name定義了屬性的名稱 -->    <attr name="custom_size" format="dimension"></attr> <!--每一個發生要定義format指定其類型,類型包括      reference  表示引用,參考某一資源ID     string  表示字串     color  表示顏色值     dimension  表示尺寸值     boolean  表示布爾值     integer  表示整型值     float  表示浮點值     fraction  表示百分數     enum  表示枚舉值     flag  表示位元運算    --> </declare-styleable>

public class CustomTextView extends TextView {  private int textSize;//自訂檔案大小  private int textColor;//自訂文字顏色  //自訂屬性,會調用帶兩個對數的構造方法  public CustomTextView(Context context, AttributeSet attrs) {    super(context, attrs);    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.custom_view);//TypedArray屬性對象    textSize = ta.getDimensionPixelSize(R.styleable.custom_view_custom_size, 20);//擷取屬性對象中對應的屬性值     textColor = ta.getColor(R.styleable.custom_view_custom_color, 0x0000ff);    setColorAndSize(textColor, textSize);//設定屬性    ta.recycle();  }  public CustomTextView(Context context) {    super(context);  }  private void setColorAndSize(int textColor, int textSize) {    setTextColor(textColor);    setTextSize(textSize);  }}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  xmlns:ldm="http://schemas.android.com/apk/res/com.ldm.learn"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:background="#f6f6f6"  android:orientation="vertical"  android:padding="10dp" >  <com.ldm.learn.CustomTextView    android:layout_width="100dp"    android:layout_height="100dp"    android:text="自訂TextView"    ldm:custom_color="#333333"    ldm:custom_size="35sp" /></LinearLayout>

布局說明:


通過以上幾步就可以實現我們想要的自訂屬性效果(用自訂屬性設定文字大小及顏色)啦!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.