綁定帳號登入

Android 台灣中文網

打印 上一主題 下一主題

[資料] Android怎麼為自定義組件註冊屬性

[複製連結] 查看: 823|回覆: 0|好評: 0
跳轉到指定樓層
樓主
暗桌之光 | 收聽TA | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
發表於 2011-6-12 12:04

馬上加入Android 台灣中文網,立即免費下載應用遊戲。

您需要 登錄 才可以下載或查看,沒有帳號?註冊

x
以下代碼通過構造函數中引入的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 就來APK.TW」,快來加入粉絲吧!
Android 台灣中文網(APK.TW)

評分

參與人數 1碎鑽 +5 幫助 +1 技術 +1 收起 理由
y776 + 5 + 1 + 1 很有幫助

查看全部評分

收藏收藏 分享分享 分享專題
用Android 就來Android 台灣中文網(https://apk.tw)
您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則