我的应用程序使用选项卡,每个选项卡都是Fragment
(来自 android.app.Fragment)。我想在其中一个中使用嵌套片段。
这是应该包含嵌套片段的顶级片段:
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import fr.epitech.test_esi.R;
public class ReservationCalendarFragment extends Fragment {
public static final int stringId = R.string.calendar_tab;
public static final String tag = "reservation_calendar_frag";
CalendarFragment t = new CalendarFragment();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = ((FragmentActivity) getActivity())
.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.calendarframelayout, t, CalendarFragment.tag);
ft.commit();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.reservation_calendar_layout, null);
}
}
}
它以编程方式使用FragmentTransaction
. 它实际上有效(我的意思是,添加了嵌套片段并且我可以看到它)但是每次我切换到另一个选项卡(因此显示另一个片段)并返回它时,嵌套片段已经消失了。
这是的代码CalendarFragment
:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;
import fr.epitech.test_esi.R;
public class CalendarFragment extends Fragment {
public static final String tag = "calendar_frag";
private SimpleDateFormat _df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragView = inflater.inflate(R.layout.calendar_layout, null);
CalendarView calendarView = (CalendarView) fragView
.findViewById(R.id.calendar);
calendarView.setOnDateChangeListener(new OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year,
int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(year, month, dayOfMonth);
Log.d("DATE", c.getTime().toString());
}
});
return fragView;
}
- 嵌套片段
CalendarFragment
扩展android.support.v4.app.Fragment
- 我的活动是
FragmentActivity
我什至尝试留在这个片段上,将活动置于后台(使用主页按钮)并恢复它,嵌套片段仍然显示。当我在应用程序的选项卡之间切换时,它确实会发生。