Я пытаюсь реализовать действие, которое использует ExpandableListView, и я дошел до сих пор, но теперь я обнаружил странное поведение.
Моя деятельность предназначена для записи потребления пищи, как указано пользователем. у них есть выбор меню (завтрак, обед и ужин - внешняя группа), которые расширяются, чтобы показать их содержание.
когда пользователь нажимает на элемент внутреннего меню, появляется диалоговое окно с запросом количества. как только они вводят количество и закрывают диалоговое окно, текст в пункте меню изменяется, чтобы отразить количество того пункта, который был потреблен
![fig 1](https://i.stack.imgur.com/BWxmm.jpg)
Приведенное выше изображение показывает список в закрытом состоянии.
ниже приведен список после того, как я открыл меню ланча и щелкнул «Картофельные чипсы» и указал количество 1. Как вы можете видеть, текст элемента «Картофель» теперь изменился и теперь отражает количество 1. *
![fig 2](https://i.stack.imgur.com/Nyi6p.jpg)
Странная часть происходит сейчас. если я нажимаю «Обед» и закрываю список, а затем снова открываю его, текст «Qty X 1» переходит на другой элемент (Молоко)
![alt text](https://i.stack.imgur.com/MopI2.jpg)
каждый раз, когда я открываю и закрываю список, он переключается между двумя пунктами. Также, если я открою другие предметы, например, завтрак, я обнаружу, что они тоже получили предметы с «Qty X 1», хотя я не щелкнул по ним.
Соответствующие биты кода:
XML для дочернего элемента:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:id="@+id/childname"
android:paddingLeft="50dip"
android:textSize="14dip"
android:textStyle="italic"
android:layout_width="200dip"
android:textColor="@color/black"
android:layout_height="40dip"/>
<TextView android:id="@+id/qty_display"
android:text="-"
android:textSize="14dip"
android:textStyle="italic"
android:layout_width="50dip"
android:textColor="@color/black"
android:layout_height="wrap_content"/>
</LinearLayout>
Код, который срабатывает при нажатии дочернего элемента:
public boolean onChildClick(
ExpandableListView parent,
View v,
int groupPosition,
int childPosition,
long id) {
// open the dialog and inflate the buttons
myDialog = new Dialog(this);
myDialog.setTitle("Food Item Qty");
myDialog.setContentView(R.layout.food_intake_dialog);
final Button ok = (Button)myDialog.findViewById(R.id.fi_ok_but);
Button cancel = (Button)myDialog.findViewById(R.id.fi_cancel_but);
//the id for this item is stored as a hash key in a map (say, item_id01)
String key = "item_id"+groupPosition+""+childPosition;
current_selected_food_item_id = Integer.parseInt(itemMap.get(key));
// inflate the textview that shows the qty for this item on the expandablelist
barQty = (TextView) v.findViewById(R.id.qty_display);
// set the ok button to record teh quantity on press
ok.setOnClickListener(new OnClickListener() {
public void onClick(View viewParam) {
//inflate the input box that receives quantity from user
EditText fiQty = (EditText) myDialog.findViewById(R.id.fiQty);
// get the quantity and append the text on hte list item
String qty = fiQty.getText().toString();
barQty.setText("Qty X "+qty);
//open the database and save state
FoodIntake.this.application.getFoodIntakeHelper().open();
FoodIntake.this.application.getFoodIntakeHelper().storeFoodIntakeLog(current_selected_food_item_id,qty,visit_id,remote_visit_id);
String log = FoodIntake.this.application.getFoodIntakeHelper().getFoodIntakeLog(visit_id);
FoodIntake.this.application.getFoodIntakeHelper().close();
// append the main food intake list and close the dialog
list.setText("Food Intake Log:\n\n"+log);
myDialog.cancel();
}
});
Приведенный выше код открывает диалоговое окно, принимает значение для количества, добавляет элемент списка для отражения этого, также сохраняет в базе данных и устанавливает просмотр текста с выбранным элементом и количеством.
Извините, что просто выгрузил весь код, но это поставило меня в тупик и, надеюсь, кто-то может помочь.
Спасибо
Кевин