Я использую студию android для создания приложения для покупок.
Сначала я создал класс Word с двумя параметрами (товар и цена), затем создал список массивов под названием productList и добавил свои товары:
productList.add(new Word("First ", 10));
productList.add(new Word("Second ", 20));
productList.add(new Word("Third ", 30));
productList.add(new Word("Fourth ", 40));
Затем я использовал ViewPager для их отображения.
Макет каждой страницы в пейджере View состоит из двух TextView (продукт и цена), а затем значения количества и кнопки для добавления продукта в корзину и кнопку для оплаты. Макет выглядит так:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/checkoutButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Checkout"
android:onClick="startCheckout"
/>
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/white"
android:textSize="32sp"
tools:text="item" />
<TextView
android:id="@+id/secondText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/white"
android:textSize="32sp"
android:layout_marginTop="60dp"
android:layout_below="@+id/tvTitle"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="@id/secondText"
android:gravity="center"
android:layout_marginTop="16dp">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:onClick="decrement"
android:text="-" />
<TextView
android:id="@+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:text="2"
android:textColor="@android:color/black"
android:textSize="16sp" />
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:onClick="increment"
android:text="+" />
</LinearLayout>
<Button
android:id="@+id/addProductButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/btnToggle"
android:gravity="center"
android:text="add product to cart"
/>
<Button
android:id="@+id/btnToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Toggle Orientation" />
</RelativeLayout>
Я хочу добавлять цену каждый раз, когда пользователь нажимает на «addProductButton», поэтому я создал объект Button кнопки с идентификатором «addProductButton» и затем добавил к нему clickListener.
addProductButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
thisPrice = Integer.parseInt(priceTextView.getText().toString());
totalPrice += thisPrice * quantity;
totalPriceTextView.setText(String.valueOf(totalPrice));
}
});
thisPrice относится к значению int цены TextView продукта
totalPrice - это int, который я инициализировал и присвоил ему значение 0 и это относится к общей общей цене
totalPriceTextView - это TextView в другом макете, и я раздул его макет перед его инициализацией, и он относится к TextView, который будет иметь окончательную общую цену (переменная totalPrice)
переменная количества относится к целому числу, которое я уже инициализировал, и оно будет увеличиваться и уменьшаться в соответствии с методами увеличения и уменьшения каждый раз, когда пользователь нажимает кнопки «+» и «-».
Моя проблема в том, что при запуске моего приложения я не сталкиваюсь с какими-либо ошибками, но общая стоимость TextView составляет всегда показывает 0 и не обновляется до нового значения.