如何正确扩展LinearLayout来创建自定义视图



我有一些"card",这是一个简单的LinearLayout与TextView内部

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
>
 <TextView
        android:id="@+id/card_label_txt"
        android:layout_width="wrap_content"
        android:text="label" />
</LinearLayout>

然后我有我的主片段与垂直LinearLayout..在这个主片段中,我将cards添加到主布局中:

# main fragment layout
View view = inflater.inflate(R.layout.main_activity, null);
LinearLayout ll = (LinearLayout) view
                .findViewById(R.id.main_activity_ll);
# get card
View card = inflater.inflate(R.layout.card, null);
# add to fragment layout
ll.addView(card);

这个工作非常好,我的卡片填充整个宽度的片段布局。这正是我所期待的。

现在我为Card创建了一个单独的类:

Class Card extends LinearLayout{
public Card(Context context) {
        super(context);
        View view =  LayoutInflater.from(getContext()).inflate(
                R.layout.card, null);
        this.addView(view);
    }
}

然后,如果我添加我的卡片到主片段布局的方式:

# main fragment layout
View view = inflater.inflate(R.layout.main_activity, null);
LinearLayout ll = (LinearLayout) view
                .findViewById(R.id.main_activity_ll);
# add new Card to fragment layout
ll.addView(new Card(getActivity());

则添加,但卡片的宽度不再填充,而是包装到textview。

有人可以解释我为什么我得到不同的宽度大小通过这两种方法添加相同的布局?

解决方案这里是改变的卡类解决这个问题:

public Card(Context context) {
       super(context);
       LayoutInflater.from(getContext()).inflate(
                R.layout.card, this);
    }
}

这不是实现自定义视图类的正确方法。在Card类的实现中,您实际上创建了一个不需要的额外LinearLayout。

首先,实现扩展了LinearLayout的Card类。然后,在XML布局中引用它,像这样:

<com.mypackagename.Card xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
 <TextView
        android:id="@+id/card_label_txt"
        android:layout_width="wrap_content"
        android:text="label" />
</com.mypackagename.Card>

这是一个关于在android中创建自定义视图的很好的教程。

最新更新