gpt4 book ai didi

android - XML 中定义的扩展 LinearLayout 的子项不显示

转载 作者:太空宇宙 更新时间:2023-11-03 11:32:06 32 4
gpt4 key购买 nike

在我的项目中,我有很多屏幕重复相同的模式 - 它基本上是一个 View 容器,由带有标题、图像和特定背景的线性布局组成。为了避免多次复制和粘贴相同的序列,我想我可以创建一个复合 View ,扩展 LinearLayout 并在那里定义所有“样式”,然后在我的布局中使用该组件。我遵循了 howto 和示例并使我的复合 View 起作用。但是,我见过的所有示例都按如下方式使用结果 View :

<com.myproject.compound.myview
...some attrs...
/>

即没有通过 XML 添加子项。我需要像这样使用它:

<com.myproject.compound.myview
...some attrs...>
<TextView
..../>
...other views...

</com.myproject.compound.myview>

因为我正在扩展 LinearLayout,所以我希望“myview”标签也能像 LinearLayout 一样工作,但由于某些原因,我放在里面的项目没有被绘制出来。有什么我需要特别做的事情来绘制内部 View 吗?

我扩展的 LinearLayout 非常简单,我没有覆盖任何方法,只是在构造函数中调用 super 并像这样扩充布局:

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

更新:我想我应该添加一个 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:orientation="vertical"
android:background="@drawable/bg"
android:padding="12dp">
<TextView
android:id="@+id/section_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FF0000AA" />
<ImageView
android:layout_width="match_parent"
android:layout_height="2dp"
android:src="@drawable/line" />
</LinearLayout>

最佳答案

居然找到了更优雅的方案。只需要在复合 View 中使用合并标签而不是 LinearLayout。所有归结为:

<merge xmlns:android="http://schemas.android.com/apk/res/android"
<TextView
android:id="@+id/section_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="HEADING"
android:textColor="#FF0000AA" />
<ImageView
android:layout_width="match_parent"
android:layout_height="2dp"
android:src="@drawable/line" />
</merge>

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

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

主要布局:

<com.testbench.CompoundLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFDDEE"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inner text"
android:layout_gravity="center_horizontal"/>
</com.testbench.CompoundLayout>

关于android - XML 中定义的扩展 LinearLayout 的子项不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15488776/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com