【问题标题】:Android Studio calculate total priceAndroid Studio 计算总价
【发布时间】:2021-11-28 08:22:15
【问题描述】:

我想问一下如何将所有的肉饼价格相加并显示在总数中?总计在 activity_main.xml 布局中,而所有产品价格在 view_product.xml 中。 Screenshot of app 如您所见,灰色文字是每个肉饼的价格,右侧的黑色文字是乘以肉饼数量后的价格。我希望所有的黑色文本总结并显示在以下总数。

MainActivity.java

package com.tankarjian.it212n.a2910assingment;

import android.app.Activity;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.ListView;

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

public class MainActivity extends Activity {

    private Products products;
    private BaseAdapter productsAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        products = createInitialProductList();
        productsAdapter = new ProductsAdapter(products, productClickListener, getLayoutInflater());

        ListView productsListView = (ListView) findViewById(R.id.products_list);
        productsListView.setAdapter(productsAdapter);
    }

    private Products createInitialProductList() {
        return new Products(new ArrayList<>(Arrays.asList(
                new Product("Chicken Patty", 0, 4.00),
                new Product("Chicken Special Patty", 0, 5.00),
                new Product("Imported Lamb Patty", 0, 8.00),
                new Product("Imported Lamb Special Patty", 0, 10.00)

        )));
    }

    private final ProductClickListener productClickListener = new ProductClickListener() {
        @Override
        public void onMinusClick(Product product) {
            products.removeOneFrom(product);
            productsAdapter.notifyDataSetChanged();
        }

        @Override
        public void onPlusClick(Product product) {
            products.addOneTo(product);
            productsAdapter.notifyDataSetChanged();
        }
    };

    private static class Products implements ProductDataSet {

        private final List<Product> productList;

        Products(List<Product> productList) {
            this.productList = productList;
        }

        @Override
        public int size() {
            return productList.size();
        }

        @Override
        public Product get(int position) {
            return productList.get(position);
        }

        @Override
        public long getId(int position) {
            return position;
        }

        public void removeOneFrom(Product product) {
            int i = productList.indexOf(product);
            if (i == -1) {
                throw new IndexOutOfBoundsException();
            }

            Product updatedProduct = new Product(product.name, (product.quantity - 1), product.getPrice());
            productList.remove(product);
            productList.add(i, updatedProduct);
        }

        public void addOneTo(Product product) {
            int i = productList.indexOf(product);
            if (i == -1) {
                throw new IndexOutOfBoundsException();
            }
            Product updatedProduct = new Product(product.name, (product.quantity + 1), product.getPrice());
            productList.remove(product);
            productList.add(i, updatedProduct);
        }
    }

}

ProductsAdapter.java

package com.tankarjian.it212n.a2910assingment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Locale;

class ProductsAdapter extends BaseAdapter {

    private final ProductDataSet productDataSet;
    private final ProductClickListener productClickListener;
    private final LayoutInflater layoutInflater;

    ProductsAdapter(ProductDataSet productDataSet, ProductClickListener productClickListener, LayoutInflater layoutInflater) {
        this.productDataSet = productDataSet;
        this.productClickListener = productClickListener;
        this.layoutInflater = layoutInflater;
    }

    @Override
    public int getCount() {
        return productDataSet.size();
    }

    @Override
    public Product getItem(int position) {
        return productDataSet.get(position);
    }

    @Override
    public long getItemId(int position) {
        return productDataSet.getId(position);
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = createView(parent);
            view.setTag(ViewHolder.from(view));
        }

        Product Products =(Product) getItem(position);

        ImageView image = (ImageView) view.findViewById(R.id.imageBurgerView);
        image.setImageResource(R.drawable.burger);
        
        TextView text = (TextView) view.findViewById(R.id.singlePrice);
        String price = String.format(Locale.ENGLISH, "%.2f", Products.getPrice());
        text.setText(price);

        TextView text1 = (TextView) view.findViewById(R.id.totalPrice);
        String totalPrice = String.format(Locale.ENGLISH, "%.2f", (Products.getPrice() * Products.quantity));
        text1.setText(totalPrice);

        Product product = productDataSet.get(position);
        ViewHolder viewHolder = (ViewHolder) view.getTag();
        update(viewHolder, product);
        return view;


    }

    private View createView(ViewGroup parent) {
        return layoutInflater.inflate(R.layout.view_product, parent, false);
    }

    private void update(ViewHolder viewHolder, final Product product) {
        viewHolder.name.setText(product.name);
        viewHolder.quantity.setText(String.valueOf(product.quantity));
        viewHolder.minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                productClickListener.onMinusClick(product);
            }
        });
        viewHolder.plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                productClickListener.onPlusClick(product);
            }
        });
    }

    private static final class ViewHolder {
        final TextView name;
        final TextView quantity;
        final View minus;
        final View plus;

        static ViewHolder from(View view) {
            return new ViewHolder(
                    ((TextView) view.findViewById(R.id.product_name)),
                    ((TextView) view.findViewById(R.id.product_quantity)),
                    view.findViewById(R.id.product_minus),
                    view.findViewById(R.id.product_plus)

            );
        }

        private ViewHolder(TextView name, TextView quantity, View minus, View plus) {
            this.name = name;
            this.quantity = quantity;
            this.minus = minus;
            this.plus = plus;
        }
    }

}

Product.java

package com.tankarjian.it212n.a2910assingment;

class Product {
    final String name;
    final int quantity;
    private double price;

    Product(String name, int quantity, Double price) {
        this.name = name;
        this.quantity = quantity;
        this.price = price;

    }
    public double getPrice() {return price;}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
    android:layout_marginStart="15dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="15dp"
    android:layout_marginBottom="16dp"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/products_list"
        android:layout_width="0dp"
        android:layout_height="512dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Switch
        android:id="@+id/switchMember"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="48dp"
        android:text="Member"
        app:layout_constraintEnd_toEndOf="@+id/products_list"
        app:layout_constraintTop_toBottomOf="@+id/products_list" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="25dp"
        android:layout_marginStart="16dp"
        android:text="Tax "
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintBottom_toTopOf="@+id/textView3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/products_list"
        app:layout_constraintVertical_bias="0.92" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="25dp"
        android:layout_marginBottom="68dp"
        android:text="Total "
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/totalTax"
        android:layout_width="45dp"
        android:layout_height="wrap_content"
        android:text="0"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toTopOf="@+id/textView7" />

    <TextView
        android:id="@+id/textView9"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:text="RM"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toStartOf="@+id/totalTax"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/textView7"
        app:layout_constraintTop_toTopOf="@+id/textView7" />

    <TextView
        android:id="@+id/textView10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:text="RM"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toStartOf="@+id/finalTotalPrice"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/textView8"
        app:layout_constraintTop_toTopOf="@+id/textView8" />

    <TextView
        android:id="@+id/finalTotalPrice"
        android:layout_width="45dp"
        android:layout_height="wrap_content"
        android:text="0"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/textView3"
        app:layout_constraintTop_toTopOf="@+id/textView8" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="210dp"
        android:layout_height="25dp"
        android:layout_marginStart="20dp"
        android:text="--------------------------------"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toStartOf="@+id/totalTax"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toTopOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView8"
        android:layout_width="210dp"
        android:layout_height="26dp"
        android:layout_marginStart="20dp"
        android:text="--------------------------------"
        android:textColor="#2A2F49"
        android:textSize="19sp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toStartOf="@+id/finalTotalPrice"
        app:layout_constraintHorizontal_bias="0.08"
        app:layout_constraintStart_toEndOf="@+id/textView3"
        app:layout_constraintTop_toTopOf="@+id/textView3" />

</androidx.constraintlayout.widget.ConstraintLayout>

view_product.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/product_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#FF5722"
        android:textSize="20sp"
        android:textStyle="bold|italic" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageBurgerView"
            android:layout_width="70dp"
            android:layout_height="60dp"
            android:layout_marginStart="10dp"
            android:contentDescription="@string/todo"
            app:srcCompat="@drawable/burger" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_weight="1"
            android:text="@string/rm"
            android:textAlignment="textEnd"
            android:textColor="#878BA3"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/singlePrice"
            android:layout_width="108dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="3dp"
            android:layout_weight="1"
            android:text="@string/textview"
            android:textColor="#878BA3"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/rm"
            android:textAlignment="textEnd"
            android:textColor="#272E53"
            android:textSize="16sp"
            android:textStyle="bold|italic" />

        <TextView
            android:id="@+id/totalPrice"
            android:layout_width="45dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/textview"
            android:textAlignment="textStart"
            android:textColor="#272E53"
            android:textSize="16sp"
            android:textStyle="bold|italic" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="116dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/product_minus"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:text="-"
            tools:ignore="TouchTargetSizeCheck" />

        <TextView
            android:id="@+id/product_quantity"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="20"
            android:textAlignment="center"
            android:textSize="16sp"
            android:textStyle="bold" />

        <Button
            android:id="@+id/product_plus"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:text="+"
            tools:ignore="TouchTargetSizeCheck" />

    </LinearLayout>


</LinearLayout>

【问题讨论】:

    标签: java android xml android-studio


    【解决方案1】:

    view_product.xml 中,您只显示价格,但这不是实际数据所在的位置,因此您的问题不应该是价格在view_product.xml 中并且您想在activity_main.xml 中显示,而是您的问题应该是 -

    1. 数据位于何处
    2. 如何进行必要的计算
    3. 在哪里显示。 .

    您的价格数据位于products 对象中。因此,为了计算总数,您只需添加一种计算总数的方法

    private double calculateTotal(ProductDataSet productDataSet) {
        double totalPrice = 0.0;
        for(int i=0; i<productDataSet.size(); i++) {
            totalPrice += productDataSet.get(i).getPrice();
        }
    
        return totalPrice;
    }
    

    您可以将结果存储在新值中或直接显示在 textView 本身中。

    ((TextView)findViewById(R.id.finalTotalPrice)).setText(calculateTotal(products).toString());
    

    您可以在createInitialProductList() 之后的任何地方调用它。我希望这对您有所帮助并清楚。

    【讨论】:

    • 你好,我已经用你的方法计算了总额和税金。所以现在我有 calculateTotal 和 calculateTax ,我需要他们两个再次求和我该怎么做。 ` ((TextView)findViewById(R.id.finalTotal)).setText(CalculateTotal(products) + CalculateTax(products).toString()); ` 当我使用它时,它只在 R.id.finalTotal 文本视图上显示两个数字,以明确我的 calculateTotal 是 10.00 而我的 calulateTax 是 1.00,当我使用上面的设置文本时,它显示 10.01.0 而不是总和这两个 11.00。对不起,如果我的问题很愚蠢,我只是一个新手。
    • 您所犯的错误是您将字符串添加到数字中。你正在做 10.0 + "1.00"。所以这使得整个事情成为一个字符串并变成“10.01.00”。您需要做的是 (calculateTax() + calculateTotal()).toString() -> 先将数字相加,然后将结果转换为字符串。不用道歉,我们有时都是新手:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多