I'm using Tabbed Layout ("activity_carrinho"), and I have three separate fragments for each screen, product_product, client_clip, and fragment_payment. Since you needed the screens to remain intact as they passed between them, the total of the last screen does not update more according to the values of the selected products. I would like to know how I could do to pass the value to each selected item.
fragment_product:
<?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>
producto_recycler:
<android.support.v7.widget.CardView
android:id="@+id/cardProduto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/LLcardProduto">
<ImageView
android:layout_width="wrap_content"
android:layout_height="225dp"
android:src="@drawable/lanche"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/codigo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15px"
android:text="Código"
android:textSize="16sp"/>
<TextView
android:id="@+id/grupo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grupo"
android:textSize="16sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/produto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15px"
android:text="Produto"
android:textColor="#000"
android:textSize="18sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/preco"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Preço"
android:textSize="16sp"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
ProductRecycler.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<>();
private TextView precoAtual;
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) {
if (!txt.getText().toString().equals("")) {
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 < Integer.parseInt(g.getQtdItem().get(g.getItemSelecionado().size() - 1)); x++) {
soma += Float.parseFloat(g.getPrcVisProduto().get(i));
}
g.setSubTotal(soma);
g.setTotal(g.getSubTotal());
}
else{}
}
});
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) {
if (!txt.getText().toString().equals("")) {
g.setItemSelecionado(codigo.get(i));
cd.setBackgroundResource(R.drawable.selector);
cd.setAlpha((float) 0.75);
g.setQtdItem(txt.getText().toString());
float soma = g.getSubTotal();
for (int x = 0; x < Integer.parseInt(g.getQtdItem().get(g.getItemSelecionado().size() - 1)); x++) {
soma += Float.parseFloat(g.getPrcVisProduto().get(i));
}
g.setSubTotal(soma);
g.setTotal(g.getSubTotal());
}
else{}
}
});
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<Integer.parseInt(g.getQtdItem().get(g.getItemSelecionado().size()-1));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 = g.getSubTotal();
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);
g.setTotal(g.getSubTotal());
}
}
});
}
@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_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:id="@+id/pagamente_layout"
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>
<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>
activity_carriho:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.gabriel.agilmobile.CarrinhoActivity">
<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" />
</android.support.design.widget.CoordinatorLayout>
CartActivity.class
package com.example.gabriel.agilmobile;
import android.content.Intent;
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.FragmentStatePagerAdapter;
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.EditText;
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 FragmentStatePagerAdapter } 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));
mViewPager.setOffscreenPageLimit(3);
final GlobalVariable g = new GlobalVariable();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent compra = new Intent(CarrinhoActivity.this, Compra_Activity.class);
startActivity(compra);
}
});
}
@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);
GlobalVariable g = new GlobalVariable();
Spinner spFormaPag = rootView.findViewById(R.id.spnFormaPagamento);
Spinner spTiposFrete = rootView.findViewById(R.id.spnTiposFrete);
Spinner spTiposOper = rootView.findViewById(R.id.spnTiposOperacoes);
EditText frete = rootView.findViewById(R.id.frete);
EditText desconto = rootView.findViewById(R.id.desconto);
TextView subTotal = rootView.findViewById(R.id.subtotal);
TextView total = rootView.findViewById(R.id.total);
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 FragmentStatePagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
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;
}
}}