强制自定义ViewGroup子类型和计数

时间:2012-08-11 20:35:58

标签: android android-layout viewgroup

我正在通过扩展抽象类ViewGroup来制作自定义布局Android组件(根据Parleys.com上的Romain Guy的视频教程:http://www.parleys.com/#st=5&id=2191&sl=1)。

我的组件应该包含子组件,但我想将其限制为只有一个ViewGroup类型的子组件(例如另一个LinearLayout或RelativeLayout)。有点像ScrollView。有没有办法添加这个限制?

编辑: android开发人员说的最终解决方案是以编程方式检查ViewGroup子类的.FinishInflate的约束:

@Override
public void onFinishInflate()
{
    if (getChildCount() > 1)
        throw new IllegalArgumentException("Only 1 child allowed");

    if (getChildCount() == 0 || !(getChildAt(0) instanceof ViewGroup))
        throw new IllegalArgumentException("Child must be a ViewGroup");
}

2 个答案:

答案 0 :(得分:3)

确定你可以。

只需使用getChildCount()获取子项,以便检查只有一个孩子。

然后,使用getChildAt(0)获取viewGroup中唯一的子项。

在此之后,对结果使用反射并对其类进行任何额外的检查(例如,使用getSuperclass()

答案 1 :(得分:0)

让我为其他所有以自定义视图组开头的人提供此问题的答案。

当视图添加到任何类型的视图组时,可以使用的方法如下:

public void addView(View child)
public void addView(View child, int index)
public void addView(View child, int width, int height)
public void addView(View child, LayoutParams params)
public void addView(View child, int index, LayoutParams params)

无论是通过xml还是代码添加ViewGroup及其子代,都会调用其中一种方法。

现在,如果要将自定义视图组限制为特定条件。只需在这些方法中添加该条件。

以下是从ScrollView Class中获取的示例代码。

@Override
public void addView(View child) {
    if (getChildCount() > 0) {
        throw new IllegalStateException("ScrollView can host only one direct child");
    }

    super.addView(child);
}

@Override
public void addView(View child, int index) {
    if (getChildCount() > 0) {
        throw new IllegalStateException("ScrollView can host only one direct child");
    }

    super.addView(child, index);
}

@Override
public void addView(View child, ViewGroup.LayoutParams params) {
    if (getChildCount() > 0) {
        throw new IllegalStateException("ScrollView can host only one direct child");
    }

    super.addView(child, params);
}

@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
    if (getChildCount() > 0) {
        throw new IllegalStateException("ScrollView can host only one direct child");
    }

    super.addView(child, index, params);
}

提示: 在寻找某些实现时,您可能会去寻找android组件如何实现并将其作为指南实现。 :)