android - 如何正确扩展 LinearLayout 以创建自定义 View

标签 android android-layout android-fragments android-linearlayout android-context

我有一些“卡片”,它是一个简单的 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>

然后我有一个带有垂直线性布局的主 fragment 。在这个主 fragment 中,我将这个“卡片”添加到主布局中:

# 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);

这很好用,而且我的卡片填满了 fragment 布局的整个宽度。实际上是我所期待的。

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

Class Card extends LinearLayout{

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

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

        this.addView(view);

    }
}

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

# 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>

Here's a good tutorial on creating custom views in android.

关于android - 如何正确扩展 LinearLayout 以创建自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24697405/

相关文章:

android - 由于符号无效,构建失败

android - 如何在 LinearLayout 上添加 ontouchlistener 或 clicklistener?

android - 设计一个类似对话框的布局来自android中的底部

java - Android - onBackPressed 对 fragment 没有影响

java - 无法获取 fragment 中的参数

android - GCM适用于build.gradle 1.4.0,但不适用于1.3.0

android - 从字节数组 (byte[]) 转换位图 - 位图仍然为空

java - RealmModel 实现类需要仅通过 getter/setter 使用的字段吗?

android - 在菜单中添加切换按钮以停止和启动服务

java - 过滤器不工作