【问题标题】:Fragment won't launch片段不会启动
【发布时间】:2023-03-14 19:40:01
【问题描述】:

我有 onclicklistener 可以工作。我正在尝试通过单击列表视图的按钮启动一个新片段。现在,片段没有启动。但是,我们使用的模拟器并没有崩溃,所以如果我们正确理解这一点,它并没有连接到新的片段/XML 页面。

  public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    myBadData.setId(i);
    Fragment fr = new event_description();
    //fr.setArguments(bundle);
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    //int contId = v.getId();
    fragmentTransaction.add(R.id.page, fr);
   // fragmentTransaction.add(view.getId(), fr);
   // fragmentTransaction.commit();

    Intent intent =new Intent(eventList.this, fr.getClass());

}

这是我们试图在其顶部添加片段的视图的 XML 代码。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/page"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.example.alex.qtapandroid.ui.fragments.DayFragment">

<!-- TODO: Update blank fragment layout -->



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />

    <ListView
        android:id="@+id/dayList"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

 </FrameLayout>

【问题讨论】:

  • 请发布您的 LogCat,因为那里很可能有一两条错误消息。
  • 使用这一行 fragmentTransaction.commit();如果不起作用,则发布 logcat

标签: android xml android-fragments onclick


【解决方案1】:

改变这一行

Intent intent =new Intent(eventList.this, fr.getClass());

到:

fragmentTransaction.commit;

更好地替换容器中的片段,

fragmentTransaction.replace(R.id.page, fr);

【讨论】:

  • 我们应该有一个 fragmentTransaction.add 和一个 fragmentTransaction.replace 吗?
【解决方案2】:

您应该使用commit() 来启动您的事务,而不是Intent(),您还想使用replace() 而不是add()

 public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    //Assuming that this creates a new fragment
    Fragment fr = new event_description();
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction.replace(R.id.page, fr, "TAG ID");
    fragmentTransaction.commit();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    相关资源
    最近更新 更多