繁体   English   中英

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

[英]How to Correctly Extend LinearLayout to Create a Custom View

我有一些“卡片”,这是一个带有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>

然后我的主片段有一个垂直的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);

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

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

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。

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

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

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

       LayoutInflater.from(getContext()).inflate(
                R.layout.card, this);
    }
}

这不是实现自定义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>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM