Android中自訂屬性基本步驟

來源:互聯網
上載者:User

標籤:

Android中自訂屬性基本步驟

這次只是說明最簡單的自訂屬性流程

1. 建立資源檔: resources/attr.xml
<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="test">        <attr name="test" format="string" />        <attr name="testArr" format="integer" />    </declare-styleable></resources>
2. 自訂view類
public class MyTextView extends View{    private static final String TAG = "MyTextView";    public MyTextView(Context context, AttributeSet attrs) {        super(context, attrs);        TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.test);        String text = ta.getString(R.styleable.test_testArr);        int textAttr = ta.getInteger(R.styleable.test_text, -1);        Log.e(TAG, "text:"+text+",textAttr:"+textAttr);        ta.recycle();    }}
3. 在布局檔案中使用
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:yxm="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="org.xm.customview.MainActivity">    <org.xm.customview.MyTextView        android:layout_width="100dp"        android:layout_height="200dp"        yxm:testArr="20"        yxm:text="xiaoming" /></RelativeLayout>
注意

androidstudio中使用:xmlns:yxm="http://schemas.android.com/apk/res-auto"自動匯入命名控制項
如果在eclipse中要使用完成的包名,如:xmlns:sdf="http://schemas.android.com/apk/res/org.xm.customview"
給自訂屬性添加參數使用制定定義的命名空間,例如: yxm:testArr="20"

4. 實現自訂View,擷取自訂屬性
public class MyTextView extends View{    private static final String TAG = "MyTextView";    public MyTextView(Context context, AttributeSet attrs) {        super(context, attrs);        TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.test);        String text = ta.getString(R.styleable.test_text);        int textAttr = ta.getInteger(R.styleable.test_testArr, -1);        Log.e(TAG, "text:"+text+",textAttr:"+textAttr);        ta.recycle();    }}
注意

R.styleable.test_text中 text_是自動添加的(必須寫),然後添加屬性名稱字text

所以最後會列印:text:xiaoming,textAttr:20, 還是很簡單的吧!

Android中自訂屬性基本步驟

聯繫我們

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