Как изменить данные ListView в адаптере пользовательских списков? - PullRequest
0 голосов
/ 17 декабря 2018

Я пытаюсь сделать ListView из списка покупок, в котором нажатие на любую из кнопок изменяет количество конкретного товара.Это XML:

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

    <TextView
        android:id="@+id/descriptionText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="Description" />

    <TextView
        android:id="@+id/priceText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="$14.99" />

    <Button
        android:id="@+id/lessButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="lessButton"
        android:text="-" />

    <TextView
        android:id="@+id/quantityText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="0" />

    <Button
        android:id="@+id/moreButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="moreButton"
        android:text="+" />

    <TextView
        android:id="@+id/itemTotalText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="$0.00" />
</LinearLayout>

И это код Java для пользовательского адаптера, находящийся под сильным влиянием видео TheNewBoston (https://www.youtube.com/watch?v=nOdSARCVYic):

public class ListCustomAdapter extends ArrayAdapter<String>
{

public String description = "";
public double price = 0;
public Integer quantity = 0;


public ListCustomAdapter(@NonNull Context context, String[] items) {
    super(context, R.layout.custom_list_row, items);
}


@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View customView = inflater.inflate(R.layout.custom_list_row, parent, false);

    DecimalFormat df = new DecimalFormat("#,###,##0.00");

    String entry = getItem(position);
    TextView descriptionText = (TextView) customView.findViewById(R.id.descriptionText);
    TextView priceText = (TextView) customView.findViewById(R.id.priceText);
    TextView quantityText = (TextView) customView.findViewById(R.id.quantityText);
    Button lessButton = (Button) customView.findViewById(R.id.lessButton);
    Button moreButton = (Button) customView.findViewById(R.id.moreButton);

    final Integer ENTRIES = 100;
    String c = "";
    String tempString = "";
    Integer field = 0;
    //Decoding the data.
    System.out.println("String entry at position "+ position+ ": "+ entry);
    for (int a = 0; a <= entry.length()-1; a++)
    {
        c = entry.substring(a,a+1);
        System.out.println("Character line "+a+" : "+ c);
        if (!c.equals("*"))
        {
            tempString += c;
        }
        else
        {
            System.out.println("Tempstring: "+tempString);
            if (field == 0)
            {
                description = tempString;
            }
            else if (field == 1)
            {
                price = Float.valueOf(tempString);
            }
            else if (field == 2)
            {
                quantity = Integer.valueOf(tempString);
            }
            field++;
            tempString = "";
            if (field > 2)
            {
                field = 0;
            }

        }
    }


    descriptionText.setText(description);
    priceText.setText("$"+df.format(price));
    quantityText.setText(quantity.toString());

    lessButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (quantity > 0)
            {
                quantity--;
            }


        }
    });

    moreButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (quantity < ENTRIES)
            {
                quantity++;
            }


        }
    });



    return customView;
}




}

Объяснение для «Декодированияраздел "data": каждый элемент String представляет собой одну гигантскую строку, которая содержит описание, цену и количество, например, "Beef * 3.33 * 0 *". Вероятно, есть лучший способ сделать это, но это все, что я знаю сейчас.

В любом случае, на кнопке OnClickListeners, что мне нужно сделать, чтобы убедиться, что количество этого конкретного элемента изменено и отражено в ListView? Я слышал о notifyDataSetChanged (), но я неуверен, как его использовать.

1 Ответ

0 голосов
/ 17 декабря 2018

В этом случае вы можете просто установитьText в QuantityText после изменения количества.

lessButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (quantity > 0)
        {
            quantity--;
            //put this value in quantityText
            quantityText.setText(quantity.toString());
        }


    }
});

moreButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (quantity < ENTRIES)
        {
            quantity++;
            //put this value in quantityText
            quantityText.setText(quantity.toString());
        }


    }
});

Но тогда вам придется изменить «одну гигантскую строку», чтобы получить новое количество, (для некоторых возможных случаев, когда вам нужно использовать эту «одну гигантскую строку» с новыми значениями)

Лучше было бы создать класс GroceryProduct с необходимыми полями и создать объекты.(Если вы знакомы с ООП).В этом случае notifyDataSetChanged () будет особенно полезен.

...