首页 > 解决方案 > IllegalStateException:片段不与片段管理器关联

问题描述

我正在尝试从 CalendarFragment 导航到另一个 Fragment。我多次更改代码但无法使其工作。我查看了许多类似错误的解决方案,但不知道如何将它们应用于我的代码。

我的代码:

问题出在 describeEvent() 函数的末尾。错误发生在代码行FragmentManager fragmentManager = getParentFragmentManager();

public class CalendarFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{

private DatesFragment context;
FragmentTransaction fragmentTransaction;
String selectedDate;
String eventDescription;

@RequiresApi(api = Build.VERSION_CODES.N)
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    return new DatePickerDialog(requireContext(), (DatePickerDialog.OnDateSetListener)this,
            year, month, day);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_calendar, container, false);
    return view;
}

public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    selectedDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());

    describeEvent();
}

private void describeEvent() {
    View view = LayoutInflater.from(getActivity()).inflate(R.layout.description_event, null, false);
    Button ok = view.findViewById(R.id.okDescriptionId);
    Button cancel = view.findViewById(R.id.cancelDescriptionId);
    final EditText eventDescriptionUi = view.findViewById(R.id.eventDescriptionId);

    final AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
            .setView(view)
            .setCancelable(false);
    final AlertDialog descriptionAlert = builder.create();
    descriptionAlert.create();
    ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String description = eventDescriptionUi.getText().toString();
            if (description.isEmpty()) {
                eventDescriptionUi.setError("Add event description");
                return;
            } else {
                eventDescription = description;

                DatesFragment datesFragment = new DatesFragment();
                Bundle bundle = new Bundle();
                bundle.putString("description", eventDescription);
                bundle.putString("date", selectedDate);

                datesFragment.setArguments(bundle);
                FragmentManager fragmentManager = getParentFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                fragmentTransaction.replace(R.id.fragments_container, datesFragment);
                fragmentTransaction.addToBackStack(null).commit();

                descriptionAlert.dismiss();
            }
        }
    });
}}

xml 文件

日历片段:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".CalendarFragment">

  <CalendarView
     android:id="@+id/calendarView"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignParentStart="true"
     android:layout_alignParentTop="true"
     android:layout_alignParentEnd="true"
     android:layout_alignParentBottom="true"
     android:layout_marginStart="29dp"
     android:layout_marginTop="189dp"
     android:layout_marginEnd="33dp"
     android:layout_marginBottom="203dp"
     app:layout_constraintBottom_toBottomOf="parent"
     app:layout_constraintEnd_toEndOf="parent"
     app:layout_constraintStart_toStartOf="parent"
     app:layout_constraintTop_toTopOf="parent" />

警报对话框:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="wrap_content"
    android:layout_gravity="center"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
        android:layout_margin="30dp"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:text="Describe event"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="20sp"/>
    <EditText
        android:id="@+id/eventDescriptionId"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:inputType="text"
        android:textAlignment="center"
        android:hint="Describe here" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layoutDirection="ltr"
        android:orientation="horizontal">
        <Button
            android:id="@+id/okDescriptionId"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_margin="2dp"
            android:textSize="13sp"
            android:layout_weight="1"
            style="?android:attr/buttonBarButtonStyle"
            android:text="ok"/>
        <Button
            style="?android:attr/buttonBarButtonStyle"
            android:textSize="13sp"
            android:id="@+id/cancelDescriptionId"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_margin="2dp"
            android:layout_weight="1"
            android:text="cancel"/>
    </LinearLayout>
</LinearLayout>

错误信息:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.giftcalendar, PID: 29611 java.lang.IllegalStateException: Fragment CalendarFragment{324b33a} (88511445-6082-4f59-a577-6526631ac4b7)} 与片段管理器无关。在 androidx.fragment.app.Fragment.getParentFragmentManager(Fragment.java:945) 在 com.example.giftcalendar.CalendarFragment$1.onClick(CalendarFragment.java:94) 在 android.view.View.performClick(View.java:7339)在 android.widget.TextView.performClick(TextView.java:14221) 在 com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992) 在 android.view.View.performClickInternal(View.java:7305 ) 在 android.view.View.access$3200(View.java:846) 在 android.view.View$PerformClick.run(View.java:27787) 在 android.os.Handler.handleCallback(Handler.java:873) 在android.os.Handler.dispatchMessage(处理程序。

谢谢。

标签: androidandroid-fragments

解决方案


推荐阅读