Fragment won't launch

2019-03-05 05:06发布

问题:

I have onclicklistener that works. I am trying to launch a new fragment from the button click on the list view. Right now, the fragment does not launch. However, the emulator we are using does not crash, so if we're understanding this correctly, it isn't connecting to the new fragment/XML page.

  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());

}

Here is our XML code for the view that we are trying to add the fragment over top of.

<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>

回答1:

change this line

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

to:

fragmentTransaction.commit;

and better replace fragment in container ,

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


回答2:

You should be using commit() to start your transaction, not an Intent(), you also want to use replace() not 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();
}