计算价格 * 从适配器到活动总价格的数量

Posted

技术标签:

【中文标题】计算价格 * 从适配器到活动总价格的数量【英文标题】:Calculating Price * Quantity from Adapter to Total Price from Activity 【发布时间】:2022-01-04 20:11:11 【问题描述】:

我想从 Adapter 中的 Price 和 Quantity 中获取 Activity 的总价格,意思是 qty * price = total_price

这是我的适配器,用于处理项目列表Activity

package com.example.aulaherbalfinal.Adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.R;

import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;

public class AdapterDataPembelian extends RecyclerView.Adapter<AdapterDataPembelian.HolderDataPembelian>
    private Context ctx;
    private List<DataModel> listDataPembelian;
    private int count;

    public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian) 
        this.ctx = ctx;
        this.listDataPembelian = listDataPembelian;
    

    @NonNull
    @Override
    public HolderDataPembelian onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item_pembelian, parent, false);
        HolderDataPembelian holder = new HolderDataPembelian(layout);
        return holder;
    

    @Override
    public void onBindViewHolder(@NonNull HolderDataPembelian holder, int position) 
        DataModel dm = listDataPembelian.get(position);

        holder.tvId.setText(String.valueOf(dm.getId()));
        holder.tvBarang.setText(dm.getBarang());
        holder.tvStok.setText("Stok : "+String.valueOf(dm.getStok()));
        holder.tvHarga.setText(formatRupiah(Double.parseDouble(String.valueOf(dm.getHarga()))));
        holder.jmlBarang.setText(String.valueOf(dm.getQuantity()));
        //holder.totalHarga.setText(String.valueOf(dm.getTotalHarga()));
        Intent intent = new Intent("custom-message");

        holder.btnRemove.setOnClickListener(v -> 
            minusCartItem(holder,listDataPembelian.get(position));
        );

        holder.btnAdd.setOnClickListener(v -> 
            plusCartItem(holder,listDataPembelian.get(position));
        );
    

    private void plusCartItem(HolderDataPembelian holder, DataModel dataModel) 
        dataModel.setQuantity(dataModel.getQuantity()+1);
        //dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
        holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
    

    private void minusCartItem(HolderDataPembelian holder, DataModel dataModel) 
        if (dataModel.getQuantity() > 0)
            dataModel.setQuantity(dataModel.getQuantity()-1);
            //dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
            holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
         else 
            holder.jmlBarang.setText("0");
        

    

    @Override
    public int getItemCount() 
        return listDataPembelian.size();
    

    public class HolderDataPembelian extends RecyclerView.ViewHolder 
        TextView tvId, tvBarang, tvStok, tvHarga;
        Button btnAdd, btnRemove;
        TextView jmlBarang, totalHarga;

        public HolderDataPembelian(@NonNull View itemView) 
            super(itemView);

            tvId = itemView.findViewById(R.id.tv_id);
            tvBarang = itemView.findViewById(R.id.tv_barang);
            tvStok = itemView.findViewById(R.id.tv_stok);
            tvHarga = itemView.findViewById(R.id.tv_harga);
            btnAdd = itemView.findViewById(R.id.btn_add);
            btnRemove = itemView.findViewById(R.id.btn_remove);
            jmlBarang = itemView.findViewById(R.id.jml_barang);
            totalHarga = itemView.findViewById(R.id.total_harga);
        
    
    private String formatRupiah(Double number)
        Locale localeID = new Locale("IND", "ID");
        NumberFormat numberFormat = NumberFormat.getCurrencyInstance(localeID);
        String formatRupiah = numberFormat.format(number);
        String[] split = formatRupiah.split(",");
        int length = split[0].length();
        return split[0].substring(0,2)+". "+split[0].substring(2,length);
    
    public int getTotalPrice()
        int totalPrice = 0;
        for (int i=0 i<listDataPembelian.size(); i++)

        
    



这是我的活动

package com.example.aulaherbalfinal.Activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.aulaherbalfinal.API.APIRequestData;
import com.example.aulaherbalfinal.API.RetroServer;
import com.example.aulaherbalfinal.Adapter.AdapterDataPembelian;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.Model.ResponseModel;
import com.example.aulaherbalfinal.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PembelianActivity extends AppCompatActivity 
    private RecyclerView rvData;
    private RecyclerView.Adapter adData;
    private RecyclerView.LayoutManager lmData;
    private List<DataModel> listDataPembelian = new ArrayList<>();
    private SwipeRefreshLayout srlData;
    private ProgressBar pbData;
    private TextView totalHarga;
    private EditText jmlBarang;


    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pembelian);

        rvData = findViewById(R.id.rv_data);
        lmData = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rvData.setLayoutManager(lmData);
        srlData = findViewById(R.id.srl_data);
        pbData = findViewById(R.id.pb_data);
        totalHarga = findViewById(R.id.total_harga);
        jmlBarang = findViewById(R.id.jml_barang);
        totalHarga = findViewById(R.id.total_harga);
        //retrieveData();

        CardView cvTotal = findViewById(R.id.cv_total);

        rvData.setOnTouchListener(new View.OnTouchListener() 
            @Override
            public boolean onTouch(View v, MotionEvent event) 

                if (event.getAction() == MotionEvent.ACTION_MOVE)
                    cvTotal.setVisibility(View.INVISIBLE);
                
                if (event.getAction() == MotionEvent.ACTION_UP)
                    cvTotal.setVisibility(View.VISIBLE);
                
                return false;
            
        );

        BottomNavigationView bottom_navigation = findViewById(R.id.bottom_navigation);
        bottom_navigation.setItemIconTintList(null);
        bottom_navigation.setSelectedItemId(R.id.navigation_pembelian);

        ImageView profile =findViewById(R.id.profile);
        profile.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Intent intent = new Intent(PembelianActivity.this, ProfileActivity.class);
                startActivity(intent);
                finish();
            
        );

        bottom_navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() 
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) 
                switch ( (item.getItemId()))
                    case R.id.navigation_stok:
                        startActivity(new Intent(getApplicationContext(), MainActivity.class));
                        overridePendingTransition(0, 0);
                        return true;
                    case R.id.navigation_pembelian:
                        return true;
                    case R.id.navigation_penjualan:
                        startActivity(new Intent(getApplicationContext(), PenjualanActivity.class));
                        overridePendingTransition(0, 0);
                        return true;
                
                return false;
            
        );

        srlData.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() 
            @Override
            public void onRefresh() 
                srlData.setRefreshing(true);
                retrieveData();
                srlData.setRefreshing(false);
            
        );
    

    @Override
    protected void onResume() 
        super.onResume();
        retrieveData();
    

    public void retrieveData()
        pbData.setVisibility(View.VISIBLE);
        APIRequestData ardData = RetroServer.konekRetrofit().create(APIRequestData.class);
        Call<ResponseModel> tampildata = ardData.ardRetrieveData();

        tampildata.enqueue(new Callback<ResponseModel>() 
            @Override
            public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) 
                int kode = response.body().getKode();
                String pesan = response.body().getPesan();

                //Toast.makeText(MainActivity.this, "Kode : "+kode+" | Pesan : "+pesan, Toast.LENGTH_SHORT).show();

                listDataPembelian = response.body().getData();

                adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian);
                rvData.setAdapter(adData);
                adData.notifyDataSetChanged();

                pbData.setVisibility(View.INVISIBLE);
            

            @Override
            public void onFailure(Call<ResponseModel> call, Throwable t) 
                Toast.makeText(PembelianActivity.this, "Gagal Menghubungi Server", Toast.LENGTH_SHORT).show();

                pbData.setVisibility(View.INVISIBLE);
            
        );

    



Here is my app

【问题讨论】:

【参考方案1】:

我会这样做:

为您的活动创建一个接口来实现:

public interface CallbackIF 
    double tally(double amount, int quantity)



public class PembelianActivity extends AppCompatActivity implements CallbackIF 
     @Override
     public double tally(double amount, int quantity) 
         return amount * quantity;
     

然后当你初始化你的 recyclerview 适配器时,像这样在界面中传递:

adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian, PembelianActivity.this);

并将数据适配器的构造函数更改为

private CallbackIF callback;

public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian, CallbackIF callback) 
    this.ctx = ctx;
    this.listDataPembelian = listDataPembelian;
    this.callback = callback;

然后在您的列表的 onClicklistener 中/您想要触发计数的任何地方都可以调用

double value = callback.tally(amount, quantity);

如果有什么问题欢迎提问

【讨论】:

总价还是0。我想计算价格(id 是 tvHarga)* 数量(id 是 jmlBarang)。来自 recyclerview 适配器 xml 的 tvHarga 和 jmlBarang,以及来自 Activity xml 的总价(id 是 totalHarga)。我可以使用广播管理器吗?如何使用广播管理器?

以上是关于计算价格 * 从适配器到活动总价格的数量的主要内容,如果未能解决你的问题,请参考以下文章

从RecyclerView适配器更新活动或片段的视图

点击增加或者减少商品数量并且自动计算总价格

Android:根据列表视图中点击的项目计算价格。应用程序在总活动 Logcat 中崩溃:无效浮点数:“”

计算Google工作表列表中的所有唯一值+其总数量和总价格

如何从购物车中的每件商品中获取数量并传递给活动?

如何使用Django ORM查询计算数量乘以价格