如何膨胀android studio向导在活动中创建的片段(列表)?

q9yhzks0  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(294)

在androidstudio(v.4.0.1)中,file->new->fragment->fragment(list)创建一个包含所需所有组件(适配器、xmls等)的虚拟列表。保留向导给定的默认名称时,它将创建以下xml文件:
片段\u item \u list.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:name="de.afu.development.test.afu_portfolio_searcher_app_test.ItemFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context=".ItemFragment"
    tools:listitem="@layout/fragment_item" />

和fragment\u item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

<TextView
    android:id="@+id/item_number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/text_margin"
    android:textAppearance="?attr/textAppearanceListItem" />

<TextView
    android:id="@+id/content"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/text_margin"
    android:textAppearance="?attr/textAppearanceListItem" />

我可以´我不知道如何在我的活动中膨胀碎片,我尝试了:

getSupportFragmentManager().beginTransaction().add(R.id.list, new ItemFragment()).commit();

getSupportFragmentManager().beginTransaction().add(R.id.list, ItemFragment.newInstance(1)).commit();

我知道错误在'r.id.list'中,因为我得到以下stacktrace错误:

java.lang.IllegalArgumentException: No view found for id 0x7f....:id/list) for fragment ItemFragment ...

“r.id.list”是向导给recyclerview的id。
我还尝试将fragment\u item\u list.xml和fragment\u item.xml Package 到framelayout中,并从framelayout中调用r.id.blabla,我在其他答案中看到了这一点,但这也不起作用。
那么,如何在我的活动中膨胀向导创建的片段(列表),为什么我的方法不起作用?

dhxwm5r4

dhxwm5r41#

你应该吃点 ViewGroup 在你的 Activity s布局,例如。 RelativeLayout ,这将是您的 Fragment . 您正在设置 RecyclerView 作为容器,此项不起作用,因为此项不是正确的容器,并且未添加到 Activity 完全没有(所以 No view found for idException ). RecyclerView 是…的一部分 Fragment 的布局(在创建和添加之后),在其中实现了 Adapter . 将在以下时间提供 Fragment 将运行,而您正在尝试添加的线路上崩溃
Fragment .add(R.id.list, new ItemFragment()) -替换 R.id.list 把你的集装箱id充气进去 Activity (布局传递给 setContentView )

相关问题