【问题标题】:CardView is not inflating properly using LayoutInflaterCardView 没有使用 LayoutInflater 正确充气
【发布时间】:2019-11-05 21:00:58
【问题描述】:

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

但它没有正确充气。只有文本可见,卡片似乎没有出现。

【问题讨论】:

    标签: java android android-studio android-cardview layout-inflater


    【解决方案1】:

    当动态添加视图时,我们不应该用空的ViewGroup 父级来膨胀View

    在这个View view = inflater.inflate(R.layout.card_view_template, null);这里parent被指定为null,这导致了问题。

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

    因此首先声明父(根)然后创建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);
    

    【讨论】:

      【解决方案2】:

      我建议你直接使用线性布局,比如:

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

      【讨论】:

      • 这与问题的代码完全相同,但您将 parent 重命名为 LL
      • @karounka pedro kombo,不工作,仍然是同样的问题。该卡未出现。仅显示文本。如输出截图所示:“i.stack.imgur.com/fEq4A.jpg
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 2021-04-02
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      相关资源
      最近更新 更多