我的抽屉布局有四个片段
其中一个是片段被称为债务人。债务人的FragmentViewPager应该返回FragmentDebtorsForMe或FragmentDebtorsMeToOther。
我在Debtors.class中创建CategoryAdapterDebtors的方式(债务人扩展片段)
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.debtors_viewpager);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.debtors_tabs);
CategoryAdapterDebtors categoryAdapterDebtors = new CategoryAdapterDebtors
(getChildFragmentManager());
viewPager.setAdapter(categoryAdapterDebtors);
tabLayout.setupWithViewPager(viewPager);
}
扩展FragmentPagerAdapter的CategoryAdapterDebtors:
public class CategoryAdapterDebtors extends FragmentPagerAdapter {
public CategoryAdapterDebtors(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if(position==0)
return new FragmentDebtorsForMe();
if(position==1)
return new FragmentDebtorsMeToOther();
return null;
}
@Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "For me";
} else if (position == 1) {
return "Me to other";
}
return null;
}
@Override
public int getCount() {
return 2;
}
我将粘贴应该出现在ViewPager中的两个片段中的一个,因为它们具有相同的问题,并且在开始时这些类具有相同的内容。
public class FragmentDebtorsForMe extends Fragment{
private static final String TAG = FragmentDebtorsForMe.class.getSimpleName();
DatabaseClients dbClients;
List<Client> listOfClients;
public FragmentDebtorsForMe() {
Log.i(TAG, "FragmentDebtorsForMe: START");
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate: start");
super.onCreate(savedInstanceState);
listOfClients = getAllClientsFromDatabase();
Log.i(TAG, "onCreate: end");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.i(TAG, "onCreateView: START");
View rootView = inflater.inflate(R.layout.recycler, container, false);
Log.i(TAG, "onCreateView: END");
return rootView;
}
@Override
public void onAttach(Context context) {
Toast.makeText(context, "halo", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onAttach: START");
super.onAttach(context);
}
@Override
public void onDetach() {
Log.i(TAG, "onDetach: START");
super.onDetach();
}
public List<Client> getAllClientsFromDatabase() {
dbClients = new DatabaseClients(getContext());
List<Client> clients = dbClients.getAllClient();
for(Client c: clients)
Log.i(TAG, "getAllClientsFromDatabase: " + c.toString());
return clients;
}
}
问题是,当我在Fragments之间滑动时,我的任何Log.i都没有响应。
其他奇怪的事情是,在我的导航抽屉上,我点击debtors然后从FragmentDebtorsForMe和FragmentDebtorsMeToOther调用Logs,但只在ViewPager之间滑动一次,不再有。
当我为FragmentDebtorsMeToOther创建随机视图时,它正确地显示它的视图(onCreateView工作)但Log.i仍然不起作用
我不知道是什么原因导致了这个问题。
答案 0 :(得分:0)
两个片段是同时创建的,这就是您一次看到所有日志的原因。这是因为默认情况下,ViewPager会预加载下一页和上一页。您看到的减速是由于您正在onCreate()中的主线程上访问您的数据库而不是在后台线程上执行它。绝不能阻止主线程,因为它负责响应UI事件。