Android 台灣中文網

標題: Android怎麼為自定義組件註冊屬性 [打印本頁]

作者: 暗桌之光    時間: 2011-6-12 12:04
標題: Android怎麼為自定義組件註冊屬性
以下代碼通過構造函數中引入的AttributeSet 去查找XML佈局的屬性名稱,然後找到它對應引用的資源ID去找值。
  1. package com.terry.attrs;

  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.widget.EditText;
  5. import android.widget.LinearLayout;
  6. import android.widget.TextView;

  7. public class EditTextExt1 extends LinearLayout {

  8.     private String Text = "";

  9.     public EditTextExt1(Context context) {
  10.         this(context, null);
  11.         // TODO Auto-generated constructor stub
  12.     }

  13.     public EditTextExt1(Context context, AttributeSet attrs) {
  14.         super(context, attrs);
  15.         // TODO Auto-generated constructor stub
  16.         int resouceId = -1;

  17.         TextView tv = new TextView(context);
  18.         EditText et = new EditText(context);

  19.         resouceId = attrs.getAttributeResourceValue(null, "Text", 0);
  20.         if (resouceId > 0) {
  21.             Text = context.getResources().getText(resouceId).toString();
  22.         } else {
  23.             Text = "";
  24.         }
  25.         tv.setText(Text);

  26.         addView(tv);
  27.         addView(et, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
  28.                 LayoutParams.WRAP_CONTENT));
  29.         this.setGravity(LinearLayout.VERTICAL);

  30.     }

  31. }
複製代碼
如上,自定好VIEW文件就可以在XML佈局下如此使用:
  1. <com.terry.attrs.EditTextExt1 android:id="@+id/ss3"
  2.         android:layout_width="wrap_content" android:layout_height="wrap_content"
  3.         Text="@string/app_name" ></com.terry.attrs.EditTextExt1>
複製代碼





歡迎光臨 Android 台灣中文網 (https://apk.tw/) Powered by Discuz! X3.1