【发布时间】:2016-02-27 14:17:32
【问题描述】:
我有一个带有布局的自定义视图,我试图通过删除冗余的 LinearLayout 层来优化它。
我的自定义布局类似于:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/text1"
style="@style/textStyle"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/text2"
style="@style/textStyle"
/>
</merge>
我的片段的父布局类似于:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.mycompany.myprogram.MyCustomView
android:id="@+id/customView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<SomeOtherView />
<AnotherOtherView />
</LinearLayout>
</ScrollView>
</LinearLayout>
我的自定义 LinearLayout 看起来像:
public class MyCustomView extends LinearLayout {
@Bind(R.id.textView1) TextView textView1;
@Bind(R.id.textView2) TextView textView2;
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context);
}
public ConfirmEditTextSection(Context context) {
super(context);
initialize(context);
}
private void initialize(Context context) {
LayoutInflater.from(context).inflate(R.layout.layout_mycustomview, this, true);
ButterKnife.bind(this, this);
}
}
当我在膨胀后遍历子视图时,它们都在那里并且标记为可见。绑定也可以正常工作。但只有一个子视图显示在屏幕上。 LinearLayout 似乎与其内容的高度不匹配;实际上它匹配一个项目的高度,但不是两者。
如果我只是将自定义视图的 XML 布局基本类型更改为“LinearLayout”(而不是“合并”),那么两个子视图都会按预期正确显示。但是我有一个额外的 LinearLayout。
回顾一下,当使用合并时,自定义类(LinearLayout 的子类)中的子视图都存在(并且标记为可见),但屏幕上只显示一个子视图。
为了让我的 LinearLayout 自定义类正确显示它的两个子视图,我需要做一些额外的事情吗?
【问题讨论】: