0

我已经创建了自己的 ViewGroup。我已经在视图中添加了一个小部件,但我从 Eclipse 设计编辑器中得到了一个错误(我需要一个预览以实现更快/更好的开发)。

public class MyViewGroup extends LinearLayout {
    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.addView(new EditText(context));  // The Error Line
    }
...
}

使用 LayoutParams 不会改变任何东西:

this.addView(new Button(mcontext),
            new LinearLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT));

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
 <...MyViewGroup android:layout_height="match_parent" android:layout_width="match_parent" android:layout_margin="2dip" android:id="@+id/Token01">    </...MyViewGroup>
</LinearLayout>

我在模拟器上看不到。如果我删除“错误线”,设计器不会出错。什么是我失败或无法渲染 Eclipse Designer?但是为什么我在模拟器/设备上看不到它?我的目标是使用自定义视图和不带 XML 的 ViewGroup 创建此部分。

我希望你能帮助我,并为我糟糕的英语感到抱歉。

谢谢你。

4

2 回答 2

0

我尝试了以下方法,它在 Android 2.3.1 及更高版本中就像一个魅力。它不适用于 2.2 及更早版本。

public class MyViewGroup extends LinearLayout {
   public MyViewGroup(Context context, AttributeSet attrs) {
      super(context, attrs);

      if (isInEditMode()) {
         final EditText editText = new EditText(context);
         editText.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
               LayoutParams.WRAP_CONTENT));
         addView(editText);
      }
   }
}

还要注意 isInEditMode() 的用法。

于 2011-08-11T22:09:00.390 回答
0

如果我理解正确,代码中没有错误(在运行时),但可视化编辑器无法正确呈现它。
我曾经遇到过类似的问题(不完全记得),可以通过将可视化编辑器引擎更改为 Honeycomb 版本来解决它。
为此,您首先需要安装 Honeycomb SDK(API 11 或更高版本)。然后,在右上角的可视化编辑器中,您可以选择它使用的 SDK。更改为 3.x。也许这也适合你。

于 2011-08-11T21:52:39.233 回答