如何永久删除旧的片段包缓存?

时间:2017-07-14 06:48:05

标签: android android-fragments android-viewpager android-tablayout fragmentstatepageradapter

即使我在使用FragmentStatePagerAdapter时返回POSITION_NONE,我也可以看到它删除了我的片段并创建了新实例。但是新实例接收带有旧片段状态的savedInstanceState Bundle。如何彻底销毁片段,以便Bundle在再次创建时为空?

请看这是我关于SOF的第一个问题,也许我没有遵循规则来提问,但我试图尽可能地回答我的问题。如果被要求,将要求提供更多指导并提供代码。

我的代码在这里: MyAdapter.java

public class MyAdapter extends FragmentStatePagerAdapter {
public static ArrayList<Integer> page_indexes = new ArrayList<>();


FragmentTransaction mCurTransaction = null;
FragmentManager mFragmentManager ;
private List<Fragment> mFragments ;
private Fragment dummyFragment;
//public static int CURRENT_ORDER_NO = 1;

public MyAdapter(FragmentManager fm) {
    super(fm);
    mFragmentManager=fm;
    page_indexes.add(1);
}
@Override
public Fragment getItem(int position) {
    Fragment fr =  new FragmentAddOrder();
    mFragments = mFragmentManager.getFragments();
    for(int i=0;i<mFragments.size();i++){

    }
    Bundle args = new Bundle();
    args.putInt("position", position);
    fr.setArguments(args);
    return fr;
}

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

@Override
public CharSequence getPageTitle(int position) {
    return "ORDER #" + page_indexes.get(position);
}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}

public void deletePage(int position)
{
    if(page_indexes.size()>0) {
        page_indexes.remove(position);
        //mFragmentManager.popBackStackImmediate();
        notifyDataSetChanged();
        mFragments = mFragmentManager.getFragments();

        //FragmentTransaction trans = mFragmentManager.beginTransaction();
        //trans.remove(mFragments.get(position));
        //trans.commit();

    }
}
}

HomeTabActivity.java

public class HomeTabActivity extends AppCompatActivity implements View.OnClickListener {
/**
 * The current order number that helps iterate the present order number among various tabs made
 */
private int CURRENT_ORDER_NO = 1;

/**
 * The pager widget, which handles animation and allows swiping horizontally to access previous
 * and next wizard steps.
 */
public ViewPager mPager;

/**
 * The pager adapter, which provides the pages to the view pager widget.
 */
MyAdapter mAdapter;


TabLayout tabLayout;
TextView tvTotalOrders;
private Boolean isFabOpen = false;
private FloatingActionButton fabMenu, fabPrint, fabDelete, fabAddCustomer;
private Animation fab_open, fab_close, rotate_forward, rotate_backward;
// public PagerAdapter mPagerAdapter;
// private ArrayList<Integer> page_indexes;
// int orderNumber = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_tab);
    mPager = (ViewPager) findViewById(R.id.container);
    mAdapter = new MyAdapter(getSupportFragmentManager());
    // mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
    mPager.setAdapter(mAdapter);
    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    tabLayout.setupWithViewPager(mPager);
    tvTotalOrders = (TextView) findViewById(R.id.totalOrders);
    fab_close = AnimationUtils.loadAnimation(this, R.anim.fab_close);
    fab_open = AnimationUtils.loadAnimation(this, R.anim.fab_open);
    rotate_backward = AnimationUtils.loadAnimation(this, R.anim.rotate_backward);
    rotate_forward = AnimationUtils.loadAnimation(this, R.anim.rotate_forward);
    tvTotalOrders.setText("Orders Running: " + MyAdapter.page_indexes.size());
    fabMenu = (FloatingActionButton) findViewById(R.id.fabMenu);
    fabPrint = (FloatingActionButton) findViewById(R.id.fabPrint);
    fabDelete = (FloatingActionButton) findViewById(R.id.fabDelete);
    fabAddCustomer = (FloatingActionButton) findViewById(R.id.fabAddCustomer);
    fabMenu.setOnClickListener(this);
    fabPrint.setOnClickListener(this);
    fabDelete.setOnClickListener(this);
    fabAddCustomer.setOnClickListener(this);
    //page_indexes = new ArrayList<>();
    mPager.setOffscreenPageLimit(5);
    /*mAdapter.deletePage(mPager.getCurrentItem());*/
}

/**
 * Author Vibhu Jain
 * Date Created : 11 July 2017
 * Date Last Modified : 11 July 2017
 * Desc : This Function is responsible to inflate options menu in the ActionBar/ToolBar of the activity.
 * <p>
 * Last Modification:
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mymenu, menu);
    return super.onCreateOptionsMenu(menu);
}
/**
 * Author Vibhu Jain
 * Date Created : 10 July 2017
 * Date Last Modified : 11 July 2017
 * Desc : This Function is responsible for onOptions Items actions performed
 * when a certain action is selected on ActionBar OptionsMenu.
 * <p>
 * Last Modification: Added setText statement for No. of Orders running
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.addTab) {
        CURRENT_ORDER_NO += 1;
        MyAdapter.page_indexes.add(CURRENT_ORDER_NO);
        tvTotalOrders.setText("Orders Running: " + MyAdapter.page_indexes.size());
        mAdapter.notifyDataSetChanged();
        // do something here
    }        
    if (id == R.id.printAll) {
        Intent webviewIntent = new Intent(this, WebviewDemoActivity.class);
        startActivity(webviewIntent);
    }
    return super.onOptionsItemSelected(item);
}
/**
 * Author Vibhu Jain
 * Date Created : 11 July 2017
 * Date Last Modified : 13 July 2017
 * Desc : This Function is responsible for onClick actions performed
 * while clicking of Floating Action Buttons Group.
 * <p>
 * Last Modification: Added fabAddCustomer in the group with necessary onClick action as asked by Sunit Kumar.
 * Added call to webview to generate print for each order
 */
@Override
public void onClick(View view) {
    int id = view.getId();
    switch (id) {
        case R.id.fabMenu:
            animateFAB();
            break;
        case R.id.fabPrint:
            Intent webviewIntent = new Intent(this, WebviewDemoActivity.class);
            webviewIntent.putExtra("OrderNo",""+(mPager.getCurrentItem()+1));                //Toast.makeText(this,""+mPager.getCurrentItem()+1,Toast.LENGTH_LONG).show();
            startActivity(webviewIntent);
            break;
        case R.id.fabDelete:
//mPager.removeViewAt(mPager.getCurrentItem());
            //mPager.setCurrentItem(mPager.getCurrentItem()-1);
            mAdapter.deletePage(mPager.getCurrentItem());
            //mPager.setAdapter(mAdapter);
            tvTotalOrders.setText("Orders Running: " + MyAdapter.page_indexes.size());
            break;
        case R.id.fabAddCustomer:
            Intent intentDialogActivity = new Intent(getApplicationContext(), ActivityDialogCustomerAdd.class);
            startActivity(intentDialogActivity);
    }
  }
}

FragmentAddOrder.java

public class FragmentAddOrder extends Fragment {
ArrayList<String> itemsList = new ArrayList<>();
ArrayList<Integer> quantity = new ArrayList<>();
ArrayList<Double> price = new ArrayList<>();

/**
 * Declaring an ArrayAdapter to set items to ListView
 */
ArrayAdapter<String> adapter;
AutoCompleteTextView textProductView;
TextView txtEmpty;
EditText itemQuantity;
String selectedItem = "";
InputMethodManager inputMethodManager;
public static final int REQUEST_CODE = 6;
int positionNum = 1;
int positionNumSIS;
int intItemQuantity = 0;
double doubleProductPrice = 0;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    positionNum = getArguments() != null ? getArguments().getInt("position") : 1;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    setRetainInstance(false);
    return inflater.inflate(
            R.layout.activity_main, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    txtEmpty =  view.findViewById(R.id.txtEmpty);
    if (savedInstanceState != null) {
        //probably orientation change
        positionNumSIS = (int) savedInstanceState.getSerializable("positionNum");
        if (positionNumSIS == positionNum) {
            itemsList = (ArrayList<String>) savedInstanceState.getSerializable("itemsList");
            quantity = (ArrayList<Integer>) savedInstanceState.getSerializable("quantityList");
            price = (ArrayList<Double>) savedInstanceState.getSerializable("priceList");
            if (itemsList.size() >= 1) {
                txtEmpty.setText("Total Items: " + itemsList.size());
            }
        }

    }     
 //Rest of the work is my Fragment's Work to do with      
}  
/**
 * Author Vibhu Jain
 * Date Created : 11 July 2017
 * Date Last Modified : 12 July 2017
 * Desc : This Function is responsible for saving up the Fragment's List items so that they persist when a new tab is added
 * or an existing tab is deleted.
 * <p>
 * Last Modification: Added positionNum for testing purposes
 */
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("itemsList", (Serializable) itemsList);
    outState.putSerializable("quantityList", (Serializable) quantity);
    outState.putSerializable("priceList", (Serializable) price);
    outState.putSerializable("positionNum", positionNum);
}
//This function is not so usable for now, can be ignored
@Override
public void onDetach() {
    super.onDetach();
    if (this.isRemoving()) {
        FragmentManager fm = getFragmentManager();
        fm.beginTransaction().remove(this).commitAllowingStateLoss();
    }
}

}

基本上,我要做的是在viewpager中添加一些标签以获取一些订单。在添加更多选项卡的同时,保留其他选项卡中的持续数据。 如果需要删除某个选项卡,则应将其与其捆绑状态一起删除,以便其他片段(在选项卡中)不会受到影响并保留其数据。

但是现在,当我尝试删除我的标签时,它只是将标签替换为标签位置向前,并在下一个标签中移动现有片段的数据。

希望这能澄清我的问题,如果需要任何其他代码/帮助,我会立即回复。

0 个答案:

没有答案