我有一个自定义视图,我已将其包含在布局文件中,但它有一个我希望用户能够在xml文件中替换的选择模型。我已经开始查看inflater代码,但看起来它只处理调用addView()的Views。是否有其他方法可以在其他地方指定选择模型bean并在xml中引用它?
public interface SelectionModel {
public boolean isSelected(Object o);
}
public class CustomView extends View {
private SelectionModel selectionModel = new DefaultSelectionModel();
public void setSelectionModel(selectionModel) {
this.selectionModel = selectionModel;
}
}
答案 0 :(得分:0)
值/ attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="selectionModel">
<enum name="default" value="0" />
<enum name="custom" value="1" />
</attr>
</declare-styleable>
</resources>
布局
<com.example.view.CustomView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
custom:selectionModel="default"/>
public class CustomView extends View {
private static final int SELECTION_MODEL_DEFAULT = 0;
private static final int SELECTION_MODEL_CUSTOM = 1;
private SelectionModel mSelectionModel;
public CustomView(Context context) {
super(context);
mSelectionModel = new DefaultSelectionModel();
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
checkAttrubites(context, attrs);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
checkAttrubites(context, attrs);
}
private void checkAttrubites(final Context context, final AttributeSet attrs) {
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
switch (a.getInt(R.styleable.CustomView_selectionModel, 0)) {
case SELECTION_MODEL_CUSTOM:
mSelectionModel = new CustomSelectionModel();
break;
case SELECTION_MODEL_DEFAULT:
defualt:
mSelectionModel = new DefaultSelectionModel();
break;
}
a.recycle();
}
}