Question

How to naturally invoke android.view.InflateException whilst instantiation a layout XML file into a corresponding View object? Erasure of the constructor with AttributeSet parameter and throw is prohibited.

Use set of typical constructors:

public TestView(Context context) {
    this(context, null);
}

public TestView(Context context, AttributeSet attrs) {
    this(context, attrs, com.android.internal.R.attr.gridViewStyle);
}

public TestView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    TypedArray a = context.obtainStyledAttributes(attrs,
            com.android.internal.R.styleable.GridView, defStyle, 0);

    int hSpacing = a.getDimensionPixelOffset(
            com.android.internal.R.styleable.GridView_horizontalSpacing, 0);
    setHorizontalSpacing(hSpacing);

    int vSpacing = a.getDimensionPixelOffset(
            com.android.internal.R.styleable.GridView_verticalSpacing, 0);
    setVerticalSpacing(vSpacing); 

    int index = a.getInt(com.android.internal.R.styleable.GridView_stretchMode, STRETCH_COLUMN_WIDTH);
    if (index >= 0) {
        setStretchMode(index);
    }

    int columnWidth = a.getDimensionPixelOffset(com.android.internal.R.styleable.GridView_columnWidth, -1);
    if (columnWidth > 0) {
        setColumnWidth(columnWidth);
    }

    int numColumns = a.getInt(com.android.internal.R.styleable.GridView_numColumns, 1);
    setNumColumns(numColumns);

    index = a.getInt(com.android.internal.R.styleable.GridView_gravity, -1);
    if (index >= 0) {
        setGravity(index);
    }

    a.recycle();
}
Was it helpful?

Solution

Since InflateException inherits from RuntimeException you can throw it freely

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top