Android 台灣中文網
標題:
Android怎麼為自定義組件註冊屬性
[打印本頁]
作者:
暗桌之光
時間:
2011-6-12 12:04
標題:
Android怎麼為自定義組件註冊屬性
以下代碼通過構造函數中引入的AttributeSet 去查找XML佈局的屬性名稱,然後找到它對應引用的資源ID去找值。
package com.terry.attrs;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class EditTextExt1 extends LinearLayout {
private String Text = "";
public EditTextExt1(Context context) {
this(context, null);
// TODO Auto-generated constructor stub
}
public EditTextExt1(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
int resouceId = -1;
TextView tv = new TextView(context);
EditText et = new EditText(context);
resouceId = attrs.getAttributeResourceValue(null, "Text", 0);
if (resouceId > 0) {
Text = context.getResources().getText(resouceId).toString();
} else {
Text = "";
}
tv.setText(Text);
addView(tv);
addView(et, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
this.setGravity(LinearLayout.VERTICAL);
}
}
複製代碼
如上,自定好VIEW文件就可以在XML佈局下如此使用:
<com.terry.attrs.EditTextExt1 android:id="@+id/ss3"
android:layout_width="wrap_content" android:layout_height="wrap_content"
Text="@string/app_name" ></com.terry.attrs.EditTextExt1>
複製代碼
歡迎光臨 Android 台灣中文網 (https://apk.tw/)
Powered by Discuz! X3.1