首页 > 解决方案 > XML 布局未出现在 R.layout 中

问题描述

我正在使用 androidX CardView。为了为卡片制作一个 recyclerview 适配器,我需要为我制作的自定义卡片布局充气。不幸的是,自定义卡片视图的 xml 没有出现在 R.layout.(xml_name) 中,而我通常会找到所有其他布局。

这是我需要膨胀的适配器类中的代码:

public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view;
    LayoutInflater mInflater = LayoutInflater.from(mContext);
    view = mInflater.inflate(R.layout.cardview_item_answer); // not finding this layout

    return null;
}

这是卡片布局 xml (cardview_item_answer.xml):

<?xml version="1.0" encoding="utf-8"?> 
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="160dp"
android:layout_height="160dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="5dp"
app:cardCornerRadius="4dp"
>

<androidx.appcompat.widget.LinearLayoutCompat
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/image_card"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:scaleType="centerCrop"
        android:background="#2d2d2d2d">
    </androidx.appcompat.widget.AppCompatImageView>

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/text_card"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="test"
        android:textSize="13sp"
        android:textColor="@color/black"
        android:layout_gravity="center"
        ></androidx.appcompat.widget.AppCompatTextView>

</androidx.appcompat.widget.LinearLayoutCompat>

你有什么想法吗?

非常感谢 !

标签: javaandroidandroid-studioandroid-recyclerviewandroid-xml

解决方案


如果 XML 包含任何错误,您的构建可能会失败 - 这将导致 R.layout 产生意外结果。我在 cardview_item_answer.xml 中没有看到 CardView 的结束标记

尝试</androidx.cardview.widget.CardView>在 cardview_item_answer.xml 的末尾添加一个结束标签


推荐阅读