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

use*_*375 17 android android-context android-layout android-linearlayout android-fragments

我有一些"卡片",这是一个带有TextView的简单LinearLayout

<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>
Run Code Online (Sandbox Code Playgroud)

然后我的主片段有一个垂直的LinearLayout ..在这个主片段中我将这个"卡片"添加到主布局:

# 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);
Run Code Online (Sandbox Code Playgroud)

这非常好用我的卡填充片段布局的整个宽度.实际上我在期待什么.

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

Class Card extends LinearLayout{

public Card(Context context) {
        super(context);

        View view =  LayoutInflater.from(getContext()).inflate(
                R.layout.card, null);

        this.addView(view);

    }
}
Run Code Online (Sandbox Code Playgroud)

然后,如果我将卡添加到主片段布局中:

# 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());
Run Code Online (Sandbox Code Playgroud)

然后它被添加但卡的宽度不再填充,但包裹到textview.

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

此处的解决方案已更改解决此问题的Card类:

public Card(Context context) {
       super(context);

       LayoutInflater.from(getContext()).inflate(
                R.layout.card, this);
    }
}
Run Code Online (Sandbox Code Playgroud)

SBe*_*413 17

这不是实现自定义View类的正确方法.在您实现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>
Run Code Online (Sandbox Code Playgroud)

这是一个关于在an​​droid中创建自定义视图的好教程.