【问题标题】:How to populate a compound viewgroup extending from LinearLayout?如何填充从 LinearLayout 扩展的复合视图组?
【发布时间】:2011-06-29 22:42:59
【问题描述】:

我试图在从 XML 文件扩充组后创建一个复合视图组。

视图组由:一个LinearLayout Root,2个子LinearLayouts组成。我能够在布局编辑器中正确查看布局;但是,当我尝试从编辑器中添加视图(例如按钮)时,视图不会显示并且应用程序会立即强制关闭。有人告诉我,我可能需要重写 onLayout 方法才能正确绘制视图组件,但我很困惑。

我的班级:

public class FocusBox extends LinearLayout {
private LinearLayout    rootLayout,
                        contentLayout,
                        topLayout;

public FocusBox(Context context)
{
    super(context, null);
}
public FocusBox(Context context, AttributeSet attrs) {
    super(context, attrs);

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.focus_box, this);

rootLayout = (LinearLayout)findViewById(R.id.focusBoxParent);
contentLayout = (LinearLayout)findViewById(R.id.focusBottom);
topLayout = (LinearLayout)findViewById(R.id.focusTop);

}
}

还有xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp"
    android:id="@+id/focusBoxParent"
    android:orientation="vertical">
    <LinearLayout
        android:background="@drawable/gradients"
        android:layout_weight=".1"
        android:gravity="center"
        android:id="@+id/focusTop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:text="TextView"
            android:id="@+id/focusTitle"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_width="wrap_content"/>
    </LinearLayout>
    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_weight=".9"
        android:id="@+id/focusBottom"
        android:background="@drawable/gradient2"
        android:orientation="horizontal">
    </LinearLayout>
</LinearLayout>

【问题讨论】:

  • 您的问题解决了吗?我刚刚尝试了您在上面发布的相同代码,它完美无缺。我没有复制你的代码,而是独立地来到了这个解决方案,得到的代码几乎完全一样。我检查了任何值得注意的差异,但没有。

标签: android android-layout android-linearlayout layout-inflater viewgroup


【解决方案1】:

一般来说,如果您从有效的 XML 扩展布局,您应该不会收到错误。您应该进行干净的构建并再次重新部署该应用程序。 还要检查您是否在其他类的 import 语句中使用了正确的类(您可能使用来自某个 3rd-party 库的FocusBox 而不是您创建的那个)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-27
    • 2020-02-14
    • 2012-07-18
    • 1970-01-01
    • 2013-09-10
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多