【问题标题】:Custom ViewGroup自定义视图组
【发布时间】:2011-08-11 21:40:07
【问题描述】:

我已经创建了自己的 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 创建此部分。

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

谢谢。

【问题讨论】:

    标签: android android-layout android-linearlayout viewgroup


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答。代码永远不会运行。可视化编辑器显示错误并且 den Emulator 不显示 EditText。
    【解决方案2】:

    我尝试了以下方法,它在 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() 的用法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      相关资源
      最近更新 更多