How to avoid layout destroyer in Tabbed Layout when changed tab?

Asked

Viewed 40 times

0

I am making a system with tabbed layout and with Recycler view, in the first tab are the products, I click on a place the quantity and it marks the product. When I go to the third tab, the marking on the product goes away, how do I make it stop?

This is the tabbed layout:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    app:srcCompat="@drawable/seta"
    android:tint="#FFF"
    android:layout_marginBottom="20dp"
    android:layout_gravity="center|bottom"
    app:fabSize="normal"/>

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_weight="1"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:title="@string/app_name">

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TabItem
            android:id="@+id/tabItem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab_text_1" />

        <android.support.design.widget.TabItem
            android:id="@+id/tabItem2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab_text_2" />

        <android.support.design.widget.TabItem
            android:id="@+id/tabItem3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab_text_3" />

    </android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

Your class:

    package com.example.gabriel.agilmobile;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.gabriel.agilmobiel.R;
import com.example.gabriel.agilmobile.RecyclerView.ClienteRecycler;
import com.example.gabriel.agilmobile.RecyclerView.ProdutoRecycler;

import java.util.ArrayList;

public class CarrinhoActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_carrinho);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GlobalVariable g = new GlobalVariable();
                System.out.println(g.getItemSelecionado().toString());
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_carrinho, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = null;
            //Produto
            if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {
                rootView = inflater.inflate(R.layout.fragment_produto, container, false);
                RecyclerView rv = rootView.findViewById(R.id.carrinho_produto);
                GlobalVariable g = new GlobalVariable();
                RecyclerView.LayoutManager mRv = new GridLayoutManager(this.getContext(), 2);
                ProdutoRecycler adapter = new ProdutoRecycler(this.getContext(), g.getIdProduto(), g.getDescProduto(), g.getPrcVisProduto(), g.getNomeGrupo());
                rv.setAdapter(adapter);
                rv.setLayoutManager(mRv);

            }
            //Cliente
            else if(getArguments().getInt(ARG_SECTION_NUMBER)==2){
                ArrayList<String> cpfcpnj = new ArrayList<>();
                GlobalVariable g = new GlobalVariable();
                rootView = inflater.inflate(R.layout.fragment_cliente, container, false);
                for (int i=0; i<g.getIdCliente().size(); i++){
                    if (!g.getCPFCliente().get(i).equals("null") && !g.getCPFCliente().get(i).equals(null) && !g.getCPFCliente().get(i).equals("")){
                        cpfcpnj.add(g.getCPFCliente().get(i));
                    }
                    else{
                        cpfcpnj.add(g.getCNPJCliente().get(i));
                    }
                }
                RecyclerView rv =rootView.findViewById(R.id.carrinho_cliente);
                ClienteRecycler adapter = new ClienteRecycler(this.getContext(), g.getIdCliente() ,g.getCliente(), cpfcpnj);
                rv.setAdapter(adapter);
                rv.setLayoutManager(new LinearLayoutManager(this.getContext()));
            }
            //Pagamento
            else if(getArguments().getInt(ARG_SECTION_NUMBER)==3){
                rootView = inflater.inflate(R.layout.fragment_pagamento, container, false);

                Spinner spFormaPag = rootView.findViewById(R.id.spnFormaPagamento);
                Spinner spTiposFrete = rootView.findViewById(R.id.spnTiposFrete);
                Spinner spTiposOper = rootView.findViewById(R.id.spnTiposOperacoes);

                TextView subTotal = rootView.findViewById(R.id.subtotal);
                TextView total = rootView.findViewById(R.id.total);

                GlobalVariable g = new GlobalVariable();
                subTotal.setText(String.valueOf(g.getSubTotal()));
                total.setText(String.valueOf(g.getTotal()));

                ArrayAdapter<String> stFormaPag = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, g.getNomeFormaPagamento());
                ArrayAdapter<CharSequence> stTiposFrete= ArrayAdapter.createFromResource(getContext(),R.array.tiposFrete, android.R.layout.simple_spinner_item);
                ArrayAdapter<CharSequence> stTiposOper= ArrayAdapter.createFromResource(getContext(),R.array.tiposOperacao, android.R.layout.simple_spinner_item);

                stTiposFrete.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                stFormaPag.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                stTiposOper.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                spTiposFrete.setAdapter(stFormaPag);
                spFormaPag.setAdapter(stTiposFrete);
                spTiposOper.setAdapter(stTiposOper);

                spTiposFrete.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this.getContext());
                spFormaPag.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this.getContext());
                spTiposOper.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this.getContext());
            }
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }
    }}

Fragment of the product tab:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/carrinho_produto"></android.support.v7.widget.RecyclerView>
</RelativeLayout>

Product class:

package com.example.gabriel.agilmobile.RecyclerView;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.gabriel.agilmobiel.R;
import com.example.gabriel.agilmobile.GlobalVariable;

import java.util.ArrayList;

public class ProdutoRecycler extends RecyclerView.Adapter<ProdutoRecycler.MyViewHolder> {

    private static final String TAG = "ProdutoRecycler";

    private ArrayList<String> codigo = new ArrayList<>();
    private ArrayList<String> produto = new ArrayList<>();
    private ArrayList<String> preco = new ArrayList<>();
    private ArrayList<String> grupo = new ArrayList<>();
    LinearLayout cd;
    private Context context;

    public ProdutoRecycler(Context context, ArrayList<String> codigo, ArrayList<String> produto, ArrayList<String> preco, ArrayList<String> grupo){
        this.codigo = codigo;
        this.produto = produto;
        this.preco = preco;
        this.grupo = grupo;
        this.context = context;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        LinearLayout txt = (LinearLayout) LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.produto_recycler,viewGroup, false);
        ProdutoRecycler.MyViewHolder myViewHolder = new ProdutoRecycler.MyViewHolder(txt);
        return myViewHolder;
    }
    @Override
    public void onBindViewHolder(@NonNull ProdutoRecycler.MyViewHolder Holder, final int i) {
        Holder.codigo.setText(codigo.get(i));
        Holder.produto.setText(produto.get(i));
        Holder.preco.setText(preco.get(i));
        Holder.grupo.setText(grupo.get(i));
        Holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cd = v.findViewById(R.id.LLcardProduto);
                final GlobalVariable g = new GlobalVariable();
                int j=0;
                if (g.getItemSelecionado().size()==0){
                    final EditText txt = new EditText(context);
                    final AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(context);

                    // set prompts.xml to alertdialog builder
                    alertDialogBuilder1.setMessage("Informe a quantidade");
                    txt.setInputType(InputType.TYPE_CLASS_NUMBER);
                    alertDialogBuilder1.setView(txt);

                    // set dialog message
                    alertDialogBuilder1.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            g.setItemSelecionado(codigo.get(i));
                            cd.setBackgroundResource(R.drawable.selector);
                            cd.setAlpha((float) 0.75);
                            g.setQtdItem(txt.getText().toString());
                            float soma = 0;
                            for (int x=0; x<g.getItemSelecionado().size(); x++) {
                                soma += Float.parseFloat(g.getPrcVisProduto().get(i))*Float.parseFloat(g.getQtdItem().get(x));
                            }
                            g.setSubTotal(soma);
                        }
                    });
                    alertDialogBuilder1.setCancelable(false).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

                    // create alert dialog
                    AlertDialog alertDialog1 = alertDialogBuilder1.create();
                    // show it
                    alertDialog1.show();
                    System.out.println(1);
                }else if(!g.getItemSelecionado().contains(codigo.get(i))){

                    final EditText txt = new EditText(context);
                    final AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(context);
                    // set prompts.xml to alertdialog builder
                    alertDialogBuilder1.setMessage("Informe a quantidade");
                    txt.setInputType(InputType.TYPE_CLASS_NUMBER);
                    alertDialogBuilder1.setView(txt);
                    // set dialog message
                    alertDialogBuilder1.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            g.setItemSelecionado(codigo.get(i));
                            cd.setBackgroundResource(R.drawable.selector);
                            cd.setAlpha((float) 0.75);
                            g.setQtdItem(txt.getText().toString());
                            float soma = 0;
                            for (int x=0; x<g.getItemSelecionado().size(); x++) {
                                soma += Float.parseFloat(g.getPrcVisProduto().get(i))*Float.parseFloat(g.getQtdItem().get(x));
                            }
                            g.setSubTotal(soma);
                        }
                    });
                    alertDialogBuilder1.setCancelable(false).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

                    // create alert dialog
                    AlertDialog alertDialog1 = alertDialogBuilder1.create();
                    // show it
                    alertDialog1.show();
//
                }
                else{
                    System.out.println(g.getItemSelecionado().contains(codigo.get(i)));
                    for (int x=0; x<g.getItemSelecionado().size();x++){
                        if (g.getItemSelecionado().get(x)==codigo.get(i)){
                            g.getItemSelecionado().remove(x);
                            g.getQtdItem().remove(x);
                            cd.setBackgroundColor(Color.parseColor("#FFFFFF"));
                            cd.setAlpha((float) 1);
                        }
                    }
                    float soma = 0;
                    for (int x=0; x<g.getItemSelecionado().size(); x++) {
                        soma += Float.parseFloat(g.getPrcVisProduto().get(i))*Float.parseFloat(g.getQtdItem().get(x));
                    }
                    g.setSubTotal(soma);
                }
            }
        });
    }
    @Override
    public int getItemCount() {
        return produto.size();
    }
    public static class MyViewHolder extends RecyclerView.ViewHolder{
        TextView codigo;
        TextView produto;
        TextView preco;
        TextView grupo;
        LinearLayout layout;
        CardView cardView;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            codigo = itemView.findViewById(R.id.codigo);
            produto = itemView.findViewById(R.id.produto);
            preco = itemView.findViewById(R.id.preco);
            grupo = itemView.findViewById(R.id.grupo);
            layout = itemView.findViewById(R.id.layout_produto);
            cardView = itemView.findViewById(R.id.cardProduto);

        }
    }
}

Fragment of the Payment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" android:layout_margin="20dp">
    <Spinner
        android:id="@+id/spnFormaPagamento"
        android:layout_width="match_parent"
        android:layout_height="38dp"
        android:layout_marginBottom="20dp"></Spinner>
    <Spinner
        android:id="@+id/spnTiposFrete"
        android:layout_width="match_parent"
        android:layout_height="38dp"
        android:layout_marginBottom="20dp"></Spinner>
    <Spinner
        android:id="@+id/spnTiposOperacoes"
        android:layout_width="match_parent"
        android:layout_height="38dp"
        android:layout_marginBottom="20dp"></Spinner>s
    <EditText
        android:id="@+id/desconto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:hint="Desconto"
        android:inputType="number" />

    <EditText
        android:id="@+id/frete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:hint="Frete"
        android:inputType="number" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/subtotal"
        android:layout_marginBottom="20dp"
        android:text="Sub-Total"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/total"
        android:layout_marginBottom="20dp"
        android:text="Total"/>

</LinearLayout>

2 answers

1

I have practically the same problem, but it is selected, but without the borders I put when selected. I still can’t find a solution. Accompanying...

  • 1

    https://answall.com/questions/344934/como-evitar-o-destroyer-do-layout-no-tabbed-layout-quando-mudado-a-aba/345301#345301

1


You have to extend FragmentStatePagerAdapter and not FragmentPagerAdapter.

to tell how many screens you want to keep open, use the method: seuViewPager.setOffscreenPageLimit(2)

  • 1

    Thank you very much, that’s just what I needed

  • If you can, approve my reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.