There is a fragment, and it's xml markup contains ViewPager
. Within this fragment it's necessary to implement navigation in other fragments by swipe.
public class MainFragment extends Fragment {
private View view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.main_fragment, null);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewPager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
return view;
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
}
return fragment;
}
}
}
Everything works well. The problem is that the Fragment1
isn't possible to set own title using setTitle()
method: the title remains the same .
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment1, null);
getActivity().setTitle("Fragment 1");
return view;
}
}
What has gone wrong, and why the title of the parent Activity, which contains the MainFragment
, doesn't change when I call setTitle()
?
Thanks!
您可以使用以下方法从片段中更新活动标题:
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("My custom title");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.