3

I'm trying to build a compound control in Android, containing (among other things) a ScrollView. Things go wrong when I try to view the control in Eclipse, crashing with a NullPointerException after the error message: "Parser is not a BridgeXmlBlockParser".

Stacktrace:

java.lang.NullPointerException
at android.view.View.<init>(View.java:1720)
at android.view.ViewGroup.<init>(ViewGroup.java:277)
at android.widget.FrameLayout.<init>(FrameLayout.java:83)
at android.widget.ScrollView.<init>(ScrollView.java:128)
at android.widget.ScrollView.<init>(ScrollView.java:124)
at android.widget.ScrollView.<init>(ScrollView.java:120)
at my.compound.control.StringPicker.onMeasure(StringPicker.java:46)
...

I've traced the error to the following conditions:

  • The NPE is thrown because a Context.obtainStyledAttributes() call returns null when the attrs argument passed is null.
  • This only applies to the BridgeContext implementation used in Eclipse, which expects attrs to be an instance of the BridgeXmlBlockParser.
  • The attrs argument is null because I create the ScrollView using the (Context) constructor.

There is a workaround of course, which is passing the attrs I receive when Eclipse constructs the compound control, but I don't want all the attributes set on the compound control to apply to my inner control.

Am I doing something wrong, is this a bug in Android Eclipse, ...?

This is what my.compound.control.StringPicker.onMeasure looks like (stripped it a bit for clarity):

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (this.getChildCount() != requestedLength) {
        this.removeAllViews();
        int childWidth = getWidth() / requestedLength;
        int childHeight = getHeight();
        for (int i = 0; i < requestedLength; i++) {
            ScrollView child = new ScrollView(getContext()); // NPE here
            child.setLayoutParams(new LayoutParams(childWidth, childHeight));
            addView(child);
        }
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
4

2 回答 2

1

您是如何通过 XML 布局或在代码中动态创建复合控件的?我能想到的一个可能原因是您正在通过 XML 添加它,但您可能没有添加 StringPicker(Context context, AttributeSet attrs) 构造函数。在那里你应该调用 super(context, attrs)。

于 2011-08-30T10:04:04.110 回答
0

这似乎是旧 Android 版本中的一个错误。

该问题在 Android 2.3 或更高版本中不会出现,但在选择 Android 2.2 或更低版本时会出现。这些旧 Android 版本的解决方法是(如问题中所述)attrs从构造函数复制参数。
仅当您想在这些旧版本中使用 Eclipse 中的设计视图时才需要这样做,以便在旧版本中运行您的应用程序,无需变通方法。

于 2011-08-31T09:34:02.970 回答