CardView使用LayoutInflater不能正确充气

问题描述 投票:0回答:1

我想以编程方式添加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);

See Output

到目前为止一切正常。

现在,由于要使用多个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);

但是它无法正确膨胀。仅文本是可见的,似乎没有显示卡。 See Output Here

java android android-studio android-cardview layout-inflater
1个回答
0
投票
我建议您直接使用线性布局,例如:
© www.soinside.com 2019 - 2024. All rights reserved.