若想讓自定義控件變得更加友善靈活,則就需要對控件進行定義屬性,使其用起來更友善。
下面是自定義控件屬性的方法
1、添加attrs.xml,内容格式樣式可以參考sdk\platforms\android-10\data\res\values\attrs.xml檔案
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CompoundButton">
<attr name="desc_title" format="string" />
<attr name="desc_on" format="string"/>
<attr name="desc_off" format="string"/>
</declare-styleable>
</resources>
2、在布局檔案中引用命名空間,并設定自定義屬性值,其中命名控件後面的為應用程式包名
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:frank="http://schemas.android.com/apk/res/com.frank.mobilesafe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_maintitle"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#8866ff00"
android:gravity="center"
android:text="設定中心"
android:textSize="22sp" />
<com.frank.mobilesafe.ui.SettingItemView
frank:desc_title="有新版本更新控制"
frank:desc_on="有新版本則進行更新"
frank:desc_off="不進行更新"
android:id="@+id/siv_update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
3、在自定義控件的類裡面的構造方法中對屬性值進行擷取或者設定。
public SettingItemView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
String myNamespace = "http://schemas.android.com/apk/res/com.frank.mobilesafe";
str_desc_title = attrs.getAttributeValue(myNamespace,
"desc_title");
str_desc_on = attrs.getAttributeValue(myNamespace,
"desc_on");
str_desc_off = attrs.getAttributeValue(myNamespace,
"desc_off");
tv_update_title.setText(str_desc_title);
}
4、可對自定義屬性值做其他用途的處理
/**
* 設定組合控件的狀态
*
* @param isChecked
*/
public void SetChecked(boolean isChecked) {
cb_update.setChecked(isChecked);
if(isChecked)
{
SetDesc(str_desc_on);
}
else
{
SetDesc(str_desc_off);
}
}
/**
* 設定描述資訊
*
* @param isChecked
*/
public void SetDesc(String text) {
tv_update_content.setText(text);
}
轉載于:https://www.cnblogs.com/xuhongfei/p/4014570.html