Android布局xml文件中的视图之外的其他内容?

Android布局xml文件中的视图之外的其他内容?,android,android-layout,Android,Android Layout,我有一个包含在布局文件中的自定义视图,但它有一个选择模型,我希望用户能够从xml文件中替换该模型。我已经开始研究充气机代码,但它似乎只处理调用addView的视图。是否有其他方法可以在其他地方指定选择模型bean并在xml中引用它 public interface SelectionModel { public boolean isSelected(Object o); } public class CustomView extends View { private Selec

我有一个包含在布局文件中的自定义视图,但它有一个选择模型,我希望用户能够从xml文件中替换该模型。我已经开始研究充气机代码,但它似乎只处理调用addView的视图。是否有其他方法可以在其他地方指定选择模型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;
    }
}
值/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>

这假设我了解其他CustomSelectionModel。不幸的是,由于缺乏答案,我想我已经得到了答案。我想唯一的方法是在它膨胀后以编程方式分配它。@Chris您可以创建SelectionModelFactory.fromAttributeint,这样只有factory知道您的所有选择模型。
<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();
    }

}