如何在android中使用底部导航视图时恢复片段状态?

Posted

技术标签:

【中文标题】如何在android中使用底部导航视图时恢复片段状态?【英文标题】:How to restore fragment states while using bottom navigation view in android? 【发布时间】:2019-12-02 14:51:55 【问题描述】:

我正在尝试从 android 底部导航视图中的第二个片段返回时恢复片段视图状态值(文本视图,..etc)。

MyActivity.java

public class LandingPage extends AppCompatActivity implements ProductFragment.AddToCart 

    Fragment fragment;
    TextView txtCart;
    Button btnCart;
    ItemData itemData;
    ArrayList<ItemData> itemDataList;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() 

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) 

            switch (item.getItemId()) 
                case R.id.nav_home:
                    fragment = new ProductFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.nav_profile:
                    fragment = new ReportsFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.nav_logout:
                    LogOut();
                    return true;
            
            return true;
        
    ;
 @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landing_page);

        txtCart = findViewById(R.id.txt_cart);
        btnCart = findViewById(R.id.btn_cartImg);

        itemDataList = new ArrayList<>();

        BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        loadFragment(new ProductFragment());

 private void loadFragment(Fragment fragment) 
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();
    

ProductFragment.java

public class ProductFragment extends Fragment 


    private OnFragmentInteractionListener mListener;

    Button btnCart1,btnCart2,btnCart3;
    AddToCart addToCart;
    TextView txtItem1Des,txtItem1Price,txtItem2Des,txtItem2Price,txtItem3Des,txtItem3Price;
    Button btnCart1Inc,btnCart1Dec,btnCart2Inc,btnCart2Dec,btnCart3Inc,btnCart3Dec;
    TextView cart1txt,cart2txt,cart3txt;
    String itemDes,itemPrice,itemImg,itemCount;
    int quantity1,quantity2,quantity3;

    public ProductFragment() 

    
    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);

    

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

        btnCart1 = view.findViewById(R.id.cart1);
        txtItem1Des = view.findViewById(R.id.cart1_desc);
        txtItem1Price = view.findViewById(R.id.cart1_price);
        btnCart1Inc = view.findViewById(R.id.cart1Inc);
        btnCart1Dec = view.findViewById(R.id.cart1Dec);
        cart1txt = view.findViewById(R.id.cart1txt);

        btnCart2 = view.findViewById(R.id.cart2);
        txtItem2Des = view.findViewById(R.id.cart2_desc);
        txtItem2Price = view.findViewById(R.id.cart2_price);
        btnCart2Inc = view.findViewById(R.id.cart2Inc);
        btnCart2Dec = view.findViewById(R.id.cart2Dec);
        cart2txt = view.findViewById(R.id.cart2txt);

        btnCart3 = view.findViewById(R.id.cart3);
        txtItem3Des = view.findViewById(R.id.cart3_desc);
        txtItem3Price = view.findViewById(R.id.cart3_price);
        btnCart3Inc = view.findViewById(R.id.cart3Inc);
        btnCart3Dec = view.findViewById(R.id.cart3Dec);
        cart3txt = view.findViewById(R.id.cart3txt);

        quantity1 = Integer.parseInt(cart1txt.getText().toString());
        quantity2 = Integer.parseInt(cart2txt.getText().toString());
        quantity3 = Integer.parseInt(cart3txt.getText().toString());

        buttonInitialization();
        addingToCart();

        return view;
    

    private void addingToCart() 
        btnCart1Dec.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                if(quantity1 <= 1)
                    btnCart1.setVisibility(View.VISIBLE);
                    btnCart1Dec.setVisibility(View.INVISIBLE);
                    btnCart1Inc.setVisibility(View.INVISIBLE);
                    cart1txt.setVisibility(View.INVISIBLE);
                    addToCart.removeItemFromCart(1);
                else 
                    quantity1 = quantity1-1;
                    cart1txt.setText(String.valueOf(quantity1));
                    addToCart.itemCount(cart1txt.getText().toString(),"1");
                

            
        );
        btnCart1Inc.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                quantity1 = quantity1+1;
                cart1txt.setText(String.valueOf(quantity1));
                addToCart.itemCount(cart1txt.getText().toString(),"1");
            
        );
        btnCart2Dec.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                if(quantity2 <= 1)
                    btnCart2.setVisibility(View.VISIBLE);
                    btnCart2Dec.setVisibility(View.INVISIBLE);
                    btnCart2Inc.setVisibility(View.INVISIBLE);
                    cart2txt.setVisibility(View.INVISIBLE);
                    addToCart.removeItemFromCart(2);
                else 
                    quantity2 = quantity2-1;
                    cart2txt.setText(String.valueOf(quantity2));
                    addToCart.itemCount(cart2txt.getText().toString(),"2");
                

            
        );
        btnCart2Inc.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                quantity2 = quantity2+1;
                cart2txt.setText(String.valueOf(quantity2));
                addToCart.itemCount(cart2txt.getText().toString(),"2");
            
        );
        btnCart3Dec.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                if(quantity3 <= 1)
                    btnCart3.setVisibility(View.VISIBLE);
                    btnCart3Dec.setVisibility(View.INVISIBLE);
                    btnCart3Inc.setVisibility(View.INVISIBLE);
                    cart3txt.setVisibility(View.INVISIBLE);
                    addToCart.removeItemFromCart(3);
                else 
                    quantity3 = quantity3-1;
                    cart3txt.setText(String.valueOf(quantity3));
                    addToCart.itemCount(cart3txt.getText().toString(),"3");
                

            
        );
        btnCart3Inc.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                quantity3 = quantity3+1;
                cart3txt.setText(String.valueOf(quantity3));
                addToCart.itemCount(cart3txt.getText().toString(),"3");
            
        );
    


    private void buttonInitialization() 
        btnCart1.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                    itemImg = "";
                    itemPrice = txtItem1Price.getText().toString().trim();
                    itemDes = txtItem1Des.getText().toString().trim();
                    itemCount = cart1txt.getText().toString().trim();
                    addToCart.cartCount("",itemPrice,itemDes,itemCount,"1");
                    btnCart1.setVisibility(View.INVISIBLE);
                    btnCart1Dec.setVisibility(View.VISIBLE);
                    btnCart1Inc.setVisibility(View.VISIBLE);
                    cart1txt.setVisibility(View.VISIBLE);
            
        );
        btnCart2.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                itemImg = "";
                itemPrice = txtItem2Price.getText().toString().trim();
                itemDes = txtItem2Des.getText().toString().trim();
                itemCount = cart2txt.getText().toString().trim();
                addToCart.cartCount("",itemPrice,itemDes,itemCount,"2");
                btnCart2.setVisibility(View.INVISIBLE);
                btnCart2Dec.setVisibility(View.VISIBLE);
                btnCart2Inc.setVisibility(View.VISIBLE);
                cart2txt.setVisibility(View.VISIBLE);
            
        );
        btnCart3.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                itemImg = "";
                itemPrice = txtItem3Price.getText().toString().trim();
                itemDes = txtItem3Des.getText().toString().trim();
                itemCount = cart3txt.getText().toString().trim();
                addToCart.cartCount("",itemPrice,itemDes,itemCount,"3");
                btnCart3.setVisibility(View.INVISIBLE);
                btnCart3Dec.setVisibility(View.VISIBLE);
                btnCart3Inc.setVisibility(View.VISIBLE);
                cart3txt.setVisibility(View.VISIBLE);
            
        );
    

    public void onButtonPressed(Uri uri) 
        if (mListener != null) 
            mListener.onFragmentInteraction(uri);
        
    

    @Override
    public void onAttach(Context context) 
        super.onAttach(context);
        addToCart = (AddToCart) context;
    


    @Override
    public void onDetach() 
        super.onDetach();
        mListener = null;
    
    public interface OnFragmentInteractionListener 
        void onFragmentInteraction(Uri uri);
    
   public interface AddToCart
        void cartCount(String item_img,String item_price,String item_desc,String item_count,String item_pos);
        void removeItemFromCart(int removeItem);
        void itemCount(String itemCount,String position);
    


在 ProductFragment 中,我将向文本视图添加值。当我来自 ReportFragment 时,视图值将在 ProductFragment 中被清除。

【问题讨论】:

不是替换片段,而是添加它。它会覆盖当前的。 ReportFragments 包含不同的视图。如果我们添加片段。 ProductFragment 视图将出现在 ReportFragment 中。 @amarlucky 将片段添加到堆栈,同时替换并在后按时弹出 【参考方案1】:

我会考虑分两步进行:

    保存片段实例而不是每次都重新创建一个新实例

    private ProductFragment productFragment;
    private ReportsFragment reportsFragment;
    
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() 
    
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) 
    
            switch (item.getItemId()) 
                case R.id.nav_home:
                    if(productFragment == null)
                      productFragment = new ProductFragment();
                    loadFragment(productFragment);
                    break;
                case R.id.nav_profile:
                    if(reportsFragment == null)
                      reportsFragment = new ReportsFragment();
                    loadFragment(reportsFragment);
                    break;
                case R.id.nav_logout:
                    LogOut();
                    return true;
            
            return true;
        
    ;
    

    参考this question/answer,您应该在片段中同时实现void onSaveInstanceState(final Bundle outState)void onActivityCreated(Bundle savedInstanceState)

这样,您肯定会保留片段的实例,而不是每次都创建一个新实例(new MyFragment() 将始终重新创建它)。此外,将您的视图状态保存在 onSaveInstanceState 并将其恢复到您的 onActivityCreate,将允许您保留您的视图/值。

我是在没有编译器的情况下手工编写的,所以它可能并不完美。

如果您需要更多信息,请告诉我。

祝你好运

【讨论】:

我试过它对我不起作用。我刚刚使用了这个解决方案 medium.com/@oluwabukunmi.aluko/… ,它对我有用。【参考方案2】:

我正在使用this solution,它对我有用。

【讨论】:

感谢@faranjit,您的解决方案对我有用。我从一天开始尝试。现在它工作正常。【参考方案3】:

您应该看到my detailed answer 来回答类似的问题。希望能解决你的问题。

【讨论】:

以上是关于如何在android中使用底部导航视图时恢复片段状态?的主要内容,如果未能解决你的问题,请参考以下文章

隐藏子屏幕/片段的android底部导航视图

Android - 恢复 Fragment WebView 状态以避免重新加载

通过底部导航栏更改片段时恢复片段状态

Android Studio - 在片段之间更改时底部导航崩溃

在Android中使用导航组件时如何删除默认动画过渡?

片段内容重叠工具栏和底部导航视图