处理片段的实例

时间:2016-08-01 11:51:12

标签: android fragment

我正在研究一个E-com模块。我在一个activity中实现了两个片段。一个(HomeFragment)正在容器中的活动中加载而另一个(CartFragment)正在加载放置在其上的Cart图标onClick工具栏。现在,每次当我点击购物车图标时,同一个片段一次又一次地加载,这很好,我想以同样的方式。但现在我想要无论多少次我加载相同的片段但按下后退按钮它应该去在主屏幕上。现在,当我按回键时,它将返回所有已加载的片段。我该如何解决这个问题。请帮助。

背景代码:

MainActivity

public class MainActivity extends AppCompatActivity implements HomeFragment.OnAdd,HomeFragment.OnDel,FragmentManager.OnBackStackChangedListener{

    private  int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        HomeFragment blank = new HomeFragment();
        fragmentTransaction.add(R.id.frame, blank);
        fragmentTransaction.commit();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        getSupportActionBar().setDisplayShowTitleEnabled(false);

    }

    @Override
    public void onBackPressed() {
        if (getFragmentManager().getBackStackEntryCount() > 0 ){
            getFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        //----------------CART ICON---------------------//
        MenuItem item1=menu.findItem(R.id.cart);
        item1.setIcon(buildCounterDrawable(count, R.mipmap.cart));
        //----------------SPINNER ICON------------------//
        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.spinner_list_item_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1);
        spinner.setAdapter(adapter);

        return true;
    }

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

        if (id == R.id.cart) {
            CartFragment myDetailFragment = new CartFragment();
            Bundle bundle = new Bundle();
            myDetailFragment.setArguments(bundle);
            FragmentTransaction fragmentTransaction =
                    getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.activity_main, myDetailFragment);

       fragmentTransaction.addToBackStack(null);


            fragmentTransaction.commit();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //---------------------------INFLATING BADGE------------------------------//

    private Drawable buildCounterDrawable(int count, int backgroundImageId) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
        view.setBackgroundResource(backgroundImageId);

        if (count == 0) {
            View counterTextPanel = view.findViewById(R.id.counterValuePanel);
            counterTextPanel.setVisibility(View.GONE);
        } else {
            TextView textView = (TextView) view.findViewById(R.id.count);
            textView.setText("" + count);
        }

        view.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);

        return new BitmapDrawable(getResources(), bitmap);
    }
    @Override
    public void onActionPerformedAdd(int count1) {
        count++;
        invalidateOptionsMenu();
    }

    @Override
    public void onActionPerformedDel(int count1) {
          if (count>0){
              count--;
              invalidateOptionsMenu();
          }
    }

    @Override
    public void onBackStackChanged() {

    }
}

HomeFragment

public class HomeFragment extends Fragment {


    public HomeFragment() {
        // Required empty public constructor
    }

    private Button add,del;
    private  int count = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_home, container, false);

        add=(Button)view.findViewById(R.id.add);
        del=(Button)view.findViewById(R.id.minus);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((OnAdd)getActivity()).onActionPerformedAdd(count);
            }
        });

        del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((OnDel)getActivity()).onActionPerformedDel(count);
            }
        });

        return view;
    }

    public interface OnAdd{
        void onActionPerformedAdd(int count);
    }
    public interface OnDel{
        void onActionPerformedDel(int count);
    }

}

CartFragment

public class CartFragment extends Fragment {


    public CartFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_cart, container, false);

        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);

        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);

        return view;
    }



}

2 个答案:

答案 0 :(得分:0)

Try changing your onBackPressed() implementation to

 @Override
    public void onBackPressed() {
        if (getFragmentManager().getBackStackEntryCount() > 1 ){
            while(getFragmentManager().getBackStackEntryCount() > 1){
                getFragmentManager().popBackStack();
            }
        } else {
            super.onBackPressed();
        }
    }

答案 1 :(得分:0)

您需要有两个片段容器才能实现此目的。只需切换所需片段的可见性!