从活动返回后刷新片段

时间:2016-09-02 08:05:18

标签: java android android-fragments

我正在处理一个使用TabLayout来容纳两个片段的活动。每个片段都使用RecyclerView。该活动还有一个选项菜单。单击任何选项时,将启动新活动。其中一项新活动有一个" Save"单击时按钮将更新第一个活动的数据集并返回第一个活动。但是,即使数据集本身发生变化,第一个活动的片段也不会显示已更改的数据集。

RecordAddActivity.java(第一项活动)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FileUtils.initDataDir(this);
    MySQLiteHelper db = new MySQLiteHelper(this);
    Bundle bundle = getIntent().getExtras();
    siteID = bundle.getLong(Constants.INTENT_EXTRA_SITE_ID);
    site = db.getSiteByID(siteID);
    trapFileName = site.getId() + "_" + site.getName() + ".csv";
    inputString = site.getName();

    setContentView(R.layout.activity_add_record_new);
    viewPager = (ViewPager) findViewById(R.id.view_pager);
    adapter = new PagerAdapter(getSupportFragmentManager());

    insectsAddRecordFragment = new InsectsAddRecordFragment();
    naturalPestsAddRecordFragment = new NaturalPestsAddRecordFragment();

    if (!doesRecordExist) {
        insectsAddRecordFragment.setInsects(site.getInsectsNames());
        naturalPestsAddRecordFragment.setNaturalPests(site.getNaturalPestsNames());
    } else {
        IsDefaultInsectTypes isDefaultInsectTypes = new IsDefaultInsectTypes(trapFileName);
        insectsAddRecordFragment.setInsects(isDefaultInsectTypes.getInsectNamesList());
        naturalPestsAddRecordFragment.setNaturalPests(isDefaultInsectTypes.getPestNamesList());
        site.setInsects(isDefaultInsectTypes.getInsectNamesList());
        site.setNaturalPests(isDefaultInsectTypes.getPestNamesList());
    }

    adapter.addFragment(insectsAddRecordFragment, "Serangga Perosak");
    adapter.addFragment(naturalPestsAddRecordFragment, "Musuh Semulajadi");
    viewPager.setAdapter(adapter);

    final TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayoutbar);
    tabLayout.setTabTextColors(Color.BLACK, Color.WHITE);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            super.onTabSelected(tab);
            tabLayout.requestFocus();
            hideKeyboard(viewPager);
        }
    });
} 

//The options menu which start the new activity

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_edit_insects_type){
        final int EDIT_INSECT_TYPE_REQUEST = 1;
        Intent intent = new Intent(RecordAddActivity.this, EditInsectsTypeActivity.class);
        intent.putExtra(Constants.INTENT_EXTRA_REPORT_TRAP_FILE, trapFileName);
        intent.putExtra(Constants.INTENT_EXTRA_SITE_OBJECT, site);
        startActivityForResult(intent, EDIT_INSECT_TYPE_REQUEST);
        return true;
    }
}

//The FragmentPagerAdapter

 public class PagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> mFragmentList = new ArrayList<>();

    private List<String> mFragmentTitleNames = new ArrayList<>();

    public PagerAdapter(FragmentManager fm) {
        super(fm);
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleNames.add(title);
    }

    public void swapItems(Fragment insectFragment, Fragment naturalPestFragment) {
        mFragmentList.clear();
        mFragmentList.add(insectFragment);
        mFragmentList.add(naturalPestFragment);
        Log.d(TAG, "Items swapped");
        notifyDataSetChanged();
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleNames.get(position);
    }

}

我尝试过的事情:

  1. 使用onResume()

    @Override
    public void onResume() {
    Log.d(TAG, "onResume");
    super.onResume();  // Always call the superclass method first
    doesRecordExist = FileUtils.doesRecordExists(trapFileName);
    if (doesRecordExist) {
        IsDefaultInsectTypes isDefaultInsectTypes = new IsDefaultInsectTypes(trapFileName);
        insectsAddRecordFragment = new InsectsAddRecordFragment();
        naturalPestsAddRecordFragment = new NaturalPestsAddRecordFragment();
    
        //The log shows that the data set has changed
        Log.d(TAG, "Nama serangga:" + isDefaultInsectTypes.getInsectNamesList());
    
    
        //Trying to update the fragments
        insectsAddRecordFragment.setInsects(isDefaultInsectTypes.getInsectNamesList());
        naturalPestsAddRecordFragment.setNaturalPests(isDefaultInsectTypes.getPestNamesList());
        adapter.swapItems(insectsAddRecordFragment, naturalPestsAddRecordFragment); 
        }
    }
    
  2. 使用全局变量更新片段

  3. EditInsectsTypeActivity.java(新活动)

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
    
        if (id == R.id.action_save) {
            Globals2 allowRefresh = Globals2.getInstance();
            ArrayList<String> insectsNameList = insectsViewFragment.getInsectsNameList();
            ArrayList<String> pestsNameList = naturalPestsViewFragment.getInsectsNameList();
            FileUtils.updateSiteInsects(this, trapFileName, insectsNameList, pestsNameList);
            allowRefresh.setData(true);
            Log.d(TAG, "allowRefresh: " + allowRefresh.getData());
            finish();
            Utils.showToast(getBaseContext(), "Rekod disimpan");
    
        }
        return true;
    }
    

    InsectsAddRecordFragment.java(要刷新/更新的片段)

    @Override
    public void onResume() {
        Log.d(TAG, "onResume");
        super.onResume();  // Always call the superclass method first
        Globals2 allowRefresh = Globals2.getInstance();
        IsDefaultInsectTypes isDefaultInsectTypes = new IsDefaultInsectTypes("27_Cgtv.csv");
        Log.d(TAG, "Nama serangga:" + isDefaultInsectTypes.getInsectNamesList());
        setInsects(isDefaultInsectTypes.getInsectNamesList());
        Log.d(TAG, "allowRefresh: " + allowRefresh.getData());
        if (allowRefresh.getData()) {
            allowRefresh.setData(false);
            getFragmentManager().beginTransaction().detach(this).attach(this).commit();
    
        }
    }
    

    我花了好几个小时试图解决这个问题而没有任何运气。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

覆盖:

protected void onActivityResult(int requestCode, int resultCode, Intent data)

在第一个活动中。

[编辑]有关startActivityForResult()的更多信息: https://developer.android.com/training/basics/intents/result.html

答案 1 :(得分:0)

所以,您需要执行此操作,在Activity的{​​{1}}方法中更新onPause()中的列表,如下所示:

InsectsAddRecordFragment

public void onPause() { ... // your logic for data-set changed. if (doesRecordExist) insectsAddRecordFragment.setInsects(isDefaultInsectTypes.get‌​InsectNamesList()); ... } setInsects内与此类似的内容。

InsectsAddRecordFragment

public void setInsects() { // Here adapter is the Adapter for the RecyclerView adapter.setAdapterList(isDefaultInsectTypes.get‌​InsectNamesList()); // notifyDataSetChanged() is important here because without this the Adapter has no idea // that data has changed. adapter.notifyDataSetChanged(); } 的{​​{1}}个RecyclerView项目中。执行以下操作。

RecyclerViewAdapter

使用这种方法不需要重新创建片段,而只需更新适配器中的数据集。

我还建议您在InsectsAddRecordFragment// ArrayList<String> list is just an example you may have some different data set. public void setAdapterList(ArrayList<String> list) { this.adapterList = list; } Fragments之前阅读一些博客和操作方法,然后再继续工作。