我有几个自定义 View
,我在其中创建了自定义样式属性,这些属性在 xml 布局中声明并在 View 的构造函数中读入。我的问题是,如果我在 xml 中定义我的布局时没有为所有自定义属性提供明确的值,我如何使用样式和主题来获得将传递给我的 View
的默认值的构造函数?
例如:
属性.xml:
<declare-styleable name="MyCustomView">
<attr name="customAttribute" format="float" />
</declare-styleable>
layout.xml(为简单起见删除了 android:
标签):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.mypackage" >
<-- Custom attribute defined, get 0.2 passed to constructor -->
<com.mypackage.MyCustomView
app:customAttribute="0.2" />
<-- Custom attribute not defined, get a default (say 0.4) passed to constructor -->
<com.mypackage.MyCustomView />
</LinearLayout>
最佳答案
经过更多研究,我意识到可以在构造函数中为 View
本身设置默认值。
public class MyCustomView extends View {
private float mCustomAttribute;
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray array = context.obtainStyledAttributes(attrs,
R.styleable.MyCustomView);
mCustomAttribute = array.getFloat(R.styleable.MyCustomView_customAttribute,
0.4f);
array.recycle();
}
}
默认值也可以从 xml 资源文件加载,这可能会根据屏幕尺寸、屏幕方向、SDK 版本等而有所不同。
关于android - 使用样式和主题为自定义属性创建默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10860177/