//完整代码附在文尾,前面写写改的部分
首先,我把碎片加入显示的代码是这样的:
ArrayList<Fragment> fragments = new ArrayList<>();
private void myViewPager(){
mViewPager = findViewById(R.id.myvp);
Fragment homeFragment = new HomeFragment();
Fragment missionFragment = new MissionFragment();
Fragment giftFragment = new GiftFragment();
Fragment loverFragment = new LoverFragment();
fragments.add(homeFragment);
fragments.add(missionFragment);
fragments.add(giftFragment);
fragments.add(loverFragment);
myvpAdapter myvpadapter = new myvpAdapter(getSupportFragmentManager(),
getLifecycle(), fragments);
mViewPager.setAdapter(myvpadapter);
mViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback(){
//以下自动生成的代码省略
}
}
接下来就是尝试各种搜到的方法,各种网络热门更新方案(?)全试了一遍,包括但不限于把碎片remove/replace、在onResume函数里加入更新、设一个flag如果true就重新读数据.......全部木大。
但是实话实说我觉得后两个应该是有用的,但很不幸读数据库的话getData函数根本没法单独拆出来放进onResume,虽然不能排除我能力不行的原因,但是从我花了一天查资料试图重写getData仍然失败的经历上看,这种操作大概不太好办。
还有一种方案是广播,收到消息就重载数据,听起来完美极了。结果广播写好了,能收到不假,但是接下来怎么更新?没办法,回到原点了。
一步一步loge发现是因为它依旧是加载原视图,也就是没有调onDestroyView。这时候人都改麻了也不管规范了,直接在onPause里调onDestroyView,结果毫无变化。一怒之下把onDestroy和onDetach啥的都加上,依旧毫无变化。
然,网上还有一种办法——模拟返回键退出。
确实,能退出,特别稳,就是activity怎么也被退了,我是要更新数据不是要闪退。
最后查到了一个好像很牛的复杂操作,好像是要重新生成ItemId,然后它不会把旧碎片和新碎片看作一个。大佬用的是取哈希,个人认为随机数更快一些所以用的随机数。
这个要写的是viewpager里用的adapter,
public class myvpAdapter extends FragmentStateAdapter {
List<Fragment> fragmentList = new ArrayList<>();
int targetid = getRandom();
public myvpAdapter(@NonNull FragmentManager fragmentManager,
@NonNull Lifecycle lifecycle,List<Fragment> fragments) {
super(fragmentManager, lifecycle);
fragmentList = fragments;
}
public void update(List<Fragment> fragmentList){
targetid = getRandom();
this.fragmentList = fragmentList;
//notifyDataSetChanged();
}
@Override
public long getItemId(int position) {
//targetid = getRandom();
return super.getItemId(position+targetid);
}
private int getRandom() {
Date nowDate = new Date();
long nowDateMills = nowDate.getTime();//当前时间转换为毫秒数
Random random = new Random(nowDateMills);//毫秒数作为seed
int num = random.nextInt();
return num;
}
@Override
public boolean containsItem(long itemId) {
return super.containsItem(itemId + targetid);
}
@NonNull
@Override
public Fragment createFragment(int position) {
//Log.e("TAG", "createFragment: " );
return fragmentList.get(position);
}
@Override
public int getItemCount() {
return fragmentList.size();
}
}
然后修改activity。
关键代码:if判断里面的内容
mViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
if(position == 1){//随便定一个刷新的标准,这里定的是选中第二页(会产生数据变化的fragment)
Log.e("TAG", "onPageSelected: 111");
//loverFragment.onDetach();
Fragment loverFragment = new LoverFragment();
myvpadapter.update(fragments);
Log.e("TAG", "onPageSelected: 222");
fragments.set(3, loverFragment);
}
super.onPageSelected(position);
changeTab(position);
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
完整代码
public class RunGameActivity extends AppCompatActivity implements View.OnClickListener{
//关于读数,每回合重新读/每次进游戏读全以全局变量保存
//每回合重新读并判定更快?
//优先判断事件?
ViewPager2 mViewPager;
//boolean pagerflag = true;
private LinearLayout llhome,llmission,llgift,lllover;
private ImageView ivhome,ivmission,ivgift,ivlover,ivrecent;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rungame);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
myViewPager();
myTabView();
}
private void myTabView() {
llhome = findViewById(R.id.home_baseline);
llmission = findViewById(R.id.mission_baseline);
llgift = findViewById(R.id.gift_baseline);
lllover = findViewById(R.id.lover_baseline);
ivhome = findViewById(R.id.my_home);
ivmission = findViewById(R.id.my_mission);
ivgift = findViewById(R.id.my_gift);
ivlover = findViewById(R.id.my_lover);
llhome.setOnClickListener(this);
llmission.setOnClickListener(this);
llgift.setOnClickListener(this);
lllover.setOnClickListener(this);
ivhome.setSelected(true);
ivrecent = ivhome;
}
ArrayList<Fragment> fragments = new ArrayList<>();
private void myViewPager(){
mViewPager = findViewById(R.id.myvp);
// fragments.add(GameFragment.newInstance("MyRoom"));
// fragments.add(GameFragment.newInstance("Mission"));
// fragments.add(GameFragment.newInstance("MyGift"));
// fragments.add(GameFragment.newInstance("MyLover"));
/
Fragment homeFragment = new HomeFragment();
Fragment missionFragment = new MissionFragment();
Fragment giftFragment = new GiftFragment();
Fragment loverFragment = new LoverFragment();
fragments.add(homeFragment);
fragments.add(missionFragment);
fragments.add(giftFragment);
fragments.add(loverFragment);
myvpAdapter myvpadapter = new myvpAdapter(getSupportFragmentManager(),
getLifecycle(), fragments);
mViewPager.setAdapter(myvpadapter);
mViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
if(position == 1){//随便定一个刷新的标准,这里定的是选中第二页(会产生数据变化的fragment)
Log.e("TAG", "onPageSelected: 111");
//loverFragment.onDetach();
Fragment loverFragment = new LoverFragment();
myvpadapter.update(fragments);
Log.e("TAG", "onPageSelected: 222");
fragments.set(3, loverFragment);
}
super.onPageSelected(position);
changeTab(position);
/*fragmentList = new ArrayList<>();
fragmentList.add(InfoFragmentNews.newInstance("news", mParam2/*资讯));
for (int i = 0; i < tagTypeList.size(); ++i) {
fragmentList.add(OtherProjectFragment.newInstance(tagTypeList.get(i), tags.get(i)));
}
mInfoFragmentAdapter.setFragments(fragmentList);*/
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
/
public void setFragments(ArrayList<Fragment> fragments) {
if(this.fragments != null){
FragmentTransaction ft = fragmentManager.beginTransaction();
for(Fragment f:this.fragments){
ft.remove(f);
}
ft.commit();
ft = null;
fragmentManager.executePendingTransactions();
}
this.fragments = fragments;
//notifyDataSetChanged();
}
/
private void changeTab(int position) {
ivrecent.setSelected(false);
if(position == R.id.home_baseline){
Log.e("TAG", "changeTab: "+position );
mViewPager.setCurrentItem(0);
} else if (position == R.id.mission_baseline) {
mViewPager.setCurrentItem(1);
} else if (position == R.id.gift_baseline) {
mViewPager.setCurrentItem(2);
} else if (position == R.id.lover_baseline) {
mViewPager.setCurrentItem(3);
}
switch (position){
case 0:
ivhome.setSelected(true);
ivrecent = ivhome;
break;
case 1:
ivmission.setSelected(true);
ivrecent = ivmission;
//FragmentSwitch(loverFragment, 3);
break;
case 2:
ivgift.setSelected(true);
ivrecent = ivgift;
break;
case 3:
//ivlover = find...
ivlover.setSelected(true);
ivrecent = ivlover;
break;
}
}
private void FragmentSwitch(Fragment fg, int pageId) {//pageId = R.id.XX
Log.e("TAG", "FragmentSwitch: done" );
FragmentTransaction transaction;
transaction=getSupportFragmentManager().beginTransaction();
transaction.remove(fg);
transaction.commit();
}
/*public void addData(View view) {
NPCDaoImp npcDaoImp = new NPCDaoImp(this);
//NPCData npcData = new NPCData()
npcDaoImp.addNPC();
Toast.makeText(this, "完成录入", Toast.LENGTH_SHORT).show();
}
public void searchData(View view) {
NPCDaoImp npcDaoImp = new NPCDaoImp(this);
npcDaoImp.findall();
}
public void deleteData(View view) {
NPCDaoImp npcDaoImp = new NPCDaoImp(this);
npcDaoImp.deleteall();
}
public void searchOne(View view) {
NPCDaoImp npcDaoImp = new NPCDaoImp(this);
npcDaoImp.findbyID(3);
}
public void updateOne(View view) {
NPCDaoImp npcDaoImp = new NPCDaoImp(this);
npcDaoImp.updateNPCLove(3, 10);
npcDaoImp.updateNPCLoveable(3, false);
}*/
@Override
public void onClick(View view) {
changeTab(view.getId());
}
}
运行过程: