如何将布局添加到卡片视图中?



我有一个task_layout.xml,我想以编程方式将其添加到已经与 recyclerView 配合使用的卡片视图布局文件中,该文件与 xml 文件中<include>命令配合得很好

与回收器配合使用Cardview_layout.xml查看

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="@+id/CARD_VIEW"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginVertical="8dp"
android:layout_marginHorizontal="25dp"
android:elevation="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="@+id/LIST_NAME_TEXT_VIEW"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Groceries"
android:fontFamily="@font/segoeuib"
android:textSize="21sp"
android:textColor="#000000" />
<!-- Here where i want to add the child layout -->
</RelativeLayout>
</android.support.v7.widget.CardView>

我想以编程方式添加的布局task_layout.xml,我尝试了很多东西,但它总是崩溃

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<CheckBox
android:id="@+id/CHECK_B0X_TASK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:allowUndo="true"
android:text="Task1"
android:textSize="17sp"
android:fontFamily="@font/segoeui"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"/>
<TextView
android:id="@+id/TEXT_CLOCK_TASK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9:00 AM"
android:textSize="17sp"
android:fontFamily="@font/segoeui"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>

在我键入的主要活动中,但仍然不起作用,即使XML文件中的<include>标签正常工作,它总是使应用程序崩溃

CardView cardView = findViewById(R.id.CARD_VIEW);
View child1 = LayoutInflater.from(this).inflate(R.layout.task_layout,null);
cardView.addView(child1);

试试这个...

CardView cardView = findViewById(R.id.id_cardview(;

为布局创建对象

View child1 = LayoutInflater.from(this(.inflate( R.layout.extra, null(;

cardView.addView(child1(;

最新更新