【问题标题】:How to Correctly Extend LinearLayout to Create a Custom View如何正确扩展 LinearLayout 以创建自定义视图
【发布时间】:2014-09-02 01:26:13
【问题描述】:

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

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

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

然后它被添加但卡片的宽度不再填充,而是包装到文本视图。

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

解决方案这里是改变 Card 类来解决这个问题:

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

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

【问题讨论】:

  • 你确定你的Card改变了宽度而不是LinearLayout
  • 是的。我简化了问题以便更好地理解,因为我正在处理更复杂的事情。但问题是,将“卡片”直接添加到布局中并通过新类 - 给出不同的结果。我假设通过新类添加父布局宽度无法以某种方式验证。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    相关资源
    最近更新 更多