Android涓璬eclare-styleable鎬庝箞浣跨敤
鍦ˋndroid涓紝declare-styleable鐢ㄤ簬瀹氫箟鑷畾涔夊睘鎬ч泦鍚堬紝鍙互鍦ㄥ竷灞€鏂囦欢鍜屼唬鐮佷腑浣跨敤杩欎簺灞炴€с€?/p>
棣栧厛锛屽湪res/values鏂囦欢澶逛笅鍒涘缓涓€涓猘ttrs.xml鏂囦欢锛屽畾涔?code>declare-styleable锛?/p>
<resources>
<declare-styleable name="CustomView">
<attr name="customAttribute1" format="reference" />
<attr name="customAttribute2" format="boolean" />
<attr name="customAttribute3" format="string" />
</declare-styleable>
</resources>
鐒跺悗锛屽湪甯冨眬鏂囦欢涓娇鐢ㄨ嚜瀹氫箟灞炴€э細
<com.example.CustomView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:customAttribute1="@drawable/icon"
app:customAttribute2="true"
app:customAttribute3="Hello World" />
鏈€鍚庯紝鍦ㄨ嚜瀹氫箟View鐨勪唬鐮佷腑鑾峰彇杩欎簺灞炴€у€硷細
public class CustomView extends View {
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
Drawable customAttribute1 = a.getDrawable(R.styleable.CustomView_customAttribute1);
boolean customAttribute2 = a.getBoolean(R.styleable.CustomView_customAttribute2, false);
String customAttribute3 = a.getString(R.styleable.CustomView_customAttribute3);
a.recycle();
// 浣跨敤鑾峰彇鍒扮殑灞炴€у€艰繘琛岀浉搴旀搷浣?/span>
}
}
杩欐牱灏卞彲浠ュ湪鑷畾涔塚iew涓娇鐢?code>declare-styleable瀹氫箟鐨勮嚜瀹氫箟灞炴€т簡銆?/p>