首页 > 解决方案 > CardView 没有使用 LayoutInflater 正确充气

问题描述

我想以编程方式添加 CardView。

这是我的主要活动 XML 布局 (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/linearLayout1"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical">
</LinearLayout>

这是我的 CardViewTemplate (card_view_template.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/cardViewTemplate"
    android:layout_width="160dp"
    android:layout_height="190dp"
    android:layout_margin="10dp"
    android:clickable="true"
    android:foreground="?android:selectableItemBackground">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="This is a Card" />

</androidx.cardview.widget.CardView>

这是我的 Java 代码 (MainActivity.java)

LayoutInflater inflater = getLayoutInflater();
ViewGroup parent = findViewById(R.id.linearLayout1);
inflater.inflate(R.layout.card_view_template, parent);

见输出

直到这里一切正常。

现在我想在我的activity_main.xml中的某个位置添加卡片,因为我正在使用多个 CardViews,我想在某个位置添加卡片。因此,我尝试了以下代码,而不是上面的代码:

LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.card_view_template, null);
ViewGroup parent = findViewById(R.id.linearLayout1);
parent.addView(view, 0);

但它不能正确充气。只有文本可见,卡片似乎没有出现。在此处查看输出

标签: javaandroidandroid-studioandroid-cardviewlayout-inflater

解决方案


当动态添加视图时,我们不应该View用 nullViewGroup父级膨胀。

在此View view = inflater.inflate(R.layout.card_view_template, null);此处将父级指定为空,这导致了问题。

指定将附加到的View父级,并且仅将附加到父级设置为false。这样将指定但不附加父项。

因此首先声明父(根),然后创建View并指定父(根)并将附加设置为父(根)false

这是正确的说法 View view = inflater.inflate(R.layout.card_view_template, parent, false);

因此完整的代码将是:

LayoutInflater inflater = getLayoutInflater();
ViewGroup parent = findViewById(R.id.linearLayout1);
View view = inflater.inflate(R.layout.card_view_template, parent, false);
parent.addView(view, 0);

推荐阅读