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

CardView使用LayoutInflater无法正确膨胀

一切正常,直到这里。

现在,由于要使用多个CardView,我想在 activity_main.xml 中的特定位置添加Card,我想在特定位置添加Card。因此,我尝试了以下代码,而不是上面的代码:

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

但是它不能正确膨胀。仅文本是可见的,似乎没有显示卡。

CardView使用LayoutInflater无法正确膨胀

lxt2015 回答:CardView使用LayoutInflater无法正确膨胀

我建议您直接使用线性布局,例如:

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

动态添加视图时,我们不应该将View的父级为空ViewGroup

在此View view = inflater.inflate(R.layout.card_view_template,null);中,parent被指定为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,false);
parent.addView(view,0);
本文链接:https://www.f2er.com/3156428.html

大家都在问