Android如何自訂視圖屬性_Android

來源:互聯網
上載者:User

本文執行個體為大家介紹了Android自訂視圖屬性的方法,供大家參考,具體內容如下

1. 自訂一個自己的視圖類繼承自View

public class MyView extends View{  public MyView(Context context, AttributeSet attrs)  {    super(context, attrs);    //擷取到自訂的屬性    TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.MyView);    int color=ta.getColor(R.styleable.MyView_rect_color, 0xffff0000);    setBackgroundColor(color);    //必須手動回收ta    ta.recycle();  }  public MyView(Context context)  {    super(context);  }}

2. 在res/values目錄中建立一個attrs.xml檔案

<?xml version="1.0" encoding="utf-8"?><resources>  //定義一個declare-styleable標籤,在裡面設定attr屬性  <declare-styleable name="MyView">    <attr name="rect_color" format="color"/>  </declare-styleable></resources>

一個attr屬性,對應了一個視圖屬性

3.最後看布局檔案中如何利用我們建立的自訂視圖並設定其屬性

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  //自訂一個MyView的命名空間  xmlns:gu="http://schemas.android.com/apk/res/com.gu.myrect"  xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical" >  <com.gu.myrect.MyView    android:layout_width="100dp"    android:layout_height="100dp"    //根據自訂的命名空間和我們在attrs中設定的屬性,自訂屬性值    gu:rect_color="#cc99cc" /></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.