declare-styleable是一個用于在XML文件中定義自定義View屬性的標簽。它的使用如下:
<resources>
<declare-styleable name="CustomView">
<attr name="customAttr1" format="string" />
<attr name="customAttr2" format="integer" />
</declare-styleable>
</resources>
<com.example.CustomView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/customView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:customAttr1="Hello"
app:customAttr2="123" />
public class CustomView extends View {
private String customAttr1;
private int customAttr2;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
customAttr1 = a.getString(R.styleable.CustomView_customAttr1);
customAttr2 = a.getInteger(R.styleable.CustomView_customAttr2, 0);
a.recycle();
}
}
使用declare-styleable可以方便地定義和使用自定義View的屬性,使得自定義View的屬性配置更加靈活和可擴展。