要自定义控件的declare-styleable属性,需要在res/values/attrs.xml文件中定义属性,然后在自定义控件的构造方法中获取这些属性。
<resources>
<declare-styleable name="CustomView">
<attr name="customText" format="string" />
<attr name="customTextColor" format="color" />
<attr name="customTextSize" format="dimension" />
</declare-styleable>
</resources>
public class CustomView extends View {
private String customText;
private int customTextColor;
private float customTextSize;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
customText = a.getString(R.styleable.CustomView_customText);
customTextColor = a.getColor(R.styleable.CustomView_customTextColor, Color.BLACK);
customTextSize = a.getDimension(R.styleable.CustomView_customTextSize, 12);
a.recycle();
}
// 然后可以在自定义控件中使用这些属性
}
这样就可以在布局文件中使用自定义控件并设置这些自定义属性了,例如:
<com.example.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:customText="Hello World"
app:customTextColor="@color/colorAccent"
app:customTextSize="18sp" />