我有一个片段集合: [片段1] [Fragment2] [Fragment3]
我正在使用ViewPager和FragmentPagerAdapter。我想要做的是将Fragment2替换为另一个片段(让我们称之为Fragment4),当点击Fragment2中的视图时。我正在使用以下代码:
newMsgBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
swapFragment(new Fragment4());
}
});
private void swapFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = ((FragmentActivity)getContext()).getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.view_container,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
然后当我点击newMsgBtn时,它会检测到点击但是无法更改片段。知道怎么做吗?感谢
答案 0 :(得分:1)
除了Kingfisher Phuocr answer,您可以更改此方法中的片段
@Override
public void onBackPressed() {
ArrayList myList = FragmentStatePagerAdapter.customFragmentsArrayList.remove(position);
myList.add(position,new Fragment_Number()); //i.e. your fragment number
viewPagerAdapter.notifyDataSetChanged();
}
答案 1 :(得分:0)
我认为这应该在你的FragmentStatePagerAdapter
中完成。你应该做点什么:
new FragmentStatePagerAdapter(fm) {
public int getCount() {
return fragments.size(); // the fragments list
}
public Fragment getItem(int position) {
return fragments.get(position);
}
public int getItemPosition(Object item) {
return POSITION_NONE;
}
}
每次要更改viewpager片段时,都可以调用:
fragments.remove(1); //remove your fragment 2
fragments.add(1,fragment4); // add your fragment4 into the 2 position
viewPagerAdapter.notifyDataSetChanged();
答案 2 :(得分:0)
以下是修复:
private void changeFragment(Fragment fragment) {
MainActivity activity = (MainActivity) getActivity();
activity.adapter.fragmentList.remove(0);
activity.adapter.fragmentTitleList.remove(0);
activity.adapter.fragmentList.add(0,fragment);
activity.adapter.fragmentTitleList.add(0,fragment.getClass().getSimpleName());
activity.pager.getAdapter().notifyDataSetChanged();
}
确保adapter
对象和pager
(ViewPager)实例是公开的。