我的活动是为了记录用户指定的食物摄入量。他们有菜单可供选择(早餐、午餐和晚餐-外部组),这些菜单可以扩展以显示其内容。
当用户单击内部菜单项时,会出现一个对话框,询问用户数量。一旦他们输入一个数量并关闭对话框,菜单项上的文本就会改变,以反映该项已消耗的数量
上图显示处于关闭状态的列表。
以下是我打开午餐菜单,点击“薯片”后的列表,显示数量为1。如您所见,“Potato”itemtext现在已更改为反映数量1。
奇怪的部分现在发生了。如果我单击“午餐”并关闭列表,然后再次单击它重新打开,则“数量X 1”文本已跳转到另一项(牛奶)
相关的代码位如下:
<?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();
}
});
上面的代码打开一个对话框,接受一个quantity值,附加list元素以反映这一点,还保存到数据库并设置一个包含所选项目和数量的textview。