老想着怎麼把東西寫得能夠看懂,才發現會和教是兩回事,好了,先看看效果圖
先介紹一下Demoview:第一張圖紅框内是後續的代碼
布局檔案demoview.xml如下;裡面放了一個Textview和ImageView。
這個時候如果在Activity中運用的話,就是一個死的view,那麼有沒有什麼辦法,能改變裡面的東西呢(改變文字&&設定ImageView是否顯示)
這裡就不得不提到文章标題中的attrs.xml檔案了:如下圖
寫好後是當然是運用了(其中clickable="true"是設定該控件可以點選,不設定點選變色的背景無效),圖檔中打錯個字,,,,懶得改了
其中demo_style如下:一般都是放的.9圖檔,為了友善就放個顔色了
最後當然是要将自定義的屬性實作其功能了(回到第一步中)
這兩句就是取得你在運用中輸入的東西了
其中:為了使title相當于TextView中的text:mtv.setText(),将擷取的值放入就行了。
那麼,那個boolean的值是用來幹嘛的呢:控制圖檔是否顯示–> miv.setVisibility(b ? VISIBLE : GONE);如果b為true則顯示,為false則不顯示。(拓展:了解一下VISIBLE :,GONE,INVISIBLE);
好了現在已經完成了這兩個功能了,現在來提一下,點選更換圖檔
最後在Activity中調用:
DemoView.java代碼如下:
public class DeomView extends RelativeLayout {
private ImageView miv;
private TextView mtv;
private boolean yfisshow;
public DeomView(Context context) {
this(context, null);
}
public DeomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DeomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
String title = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "title");
boolean b = attrs.getAttributeBooleanValue("http://schemas.android.com/apk/res-auto", "isshow", true);
View view = View.inflate(context, R.layout.demoview, null);
addView(view);
mtv= (TextView) view.findViewById(R.id.tv_togle);
miv = (ImageView) view.findViewById(R.id.iv_togle);
miv.setVisibility(b ? VISIBLE : GONE);
mtv.setText(title);
}
//改變狀态
public void setSetting0n(boolean isshow) {
yfisshow = isshow;
miv.setImageResource(isshow ? R.mipmap.on : R.mipmap.off);
}
//記錄狀态
public boolean issetting() {
return yfisshow;
}
public void setbackeguang() {
//第一次優化
// if (issetting()){
// setSetting0n(false);
// }else{
// setSetting0n(true);
// }
//第二次優化
// if (yfisshow){
// setSetting0n(false);
// }else{
// setSetting0n(true);
// }
//第三次優化
// if (yfisshow){
// setSetting0n(!yfisshow);
// }else{
// setSetting0n(!yfisshow);
// }
setSetting0n(!yfisshow);
}
}