標籤:des android style blog http color io ar for
若想讓自訂控制項變得更加方便靈活,則就需要對控制項進行定義屬性,使其用起來更方便。
下面是自訂控制項屬性的方法
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); }
Android開發學習筆記-自訂控制項的屬性