er的ListView包含两个TextViews和CheckBo

er的ListView包含两个TextViews和CheckBo

我在将列表项isChecked状态与同一原始内容中的复选框同步时遇到问题。我能够在列表项中设置“已检查”状态,但无法弄清楚如何设置CheckBoxes的“已检查”状态。我认为mainListView.setItemChecked应该可以完成工作,但事实并非如此。

这是我正在使用的代码:

public class Reservation_Activity extends ListActivity  {
int total=0;
private name_price[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
TextView total_tv;




/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.reservation);


    total_tv = (TextView) findViewById(R.id.total_sum);
    Button btnSave = (Button) findViewById(R.id.btnSave);
    btnSave.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(getApplicationContext(),
                    " You clicked Save button", Toast.LENGTH_SHORT).show();


        }
    });

    Button btnClear = (Button) findViewById(R.id.btnClear);
    btnClear.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            total=0;
            total_tv.setText("Pick and Send");
            Toast.makeText(getApplicationContext(),
                    " You clicked Clear button", Toast.LENGTH_SHORT).show();

            ClearSelections();
        }
    });

    // Prepare an ArrayList of todo items
    ArrayList<name_price> listTODO = PrepareListFromXml();
    this.mainListView = getListView();
    mainListView.setCacheColorHint(0);

    // Bind the data with the list
    lv_arr = (name_price[]) listTODO.toArray(lv_arr);

    mainListView.setAdapter(new MyAdapter(this,android.R.layout.simple_list_item_multiple_choice,lv_arr));

    mainListView.setItemsCanFocus(false);
    mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    mainListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
            name_price item = (name_price) mainListView.getItemAtPosition(position);

            if(mainListView.isItemChecked(position))
            {
                mainListView.setItemChecked(position, false);
                total = total - item._price;
            }  else  {
                mainListView.setItemChecked(position, true);
                total += item._price;
            }

            total_tv.setText("Total: " + total);

        }

    });


}

private void ClearSelections() {
    total=0;
    // user has clicked clear button so uncheck all the items

    int count = this.mainListView.getAdapter().getCount();

    for (int i = 0; i < count; i++) {
        this.mainListView.setItemChecked(i, false);
    }
}


private ArrayList<name_price> PrepareListFromXml() {
    ArrayList<name_price> todoItems = new ArrayList<name_price>();
    XmlResourceParser todolistXml = getResources().getXml(R.xml.order_items);
    int id=0;

    int eventType = -1;
    while (eventType != XmlResourceParser.END_DOCUMENT) {
        if (eventType == XmlResourceParser.START_TAG) {

            String strNode = todolistXml.getName();
            if (strNode.equals("item")) {
                todoItems.add(new name_price(id,todolistXml.getAttributeValue(null, "title"), Integer.parseInt(todolistXml.getAttributeValue(null, "price"))));
                id++;
            }
        }

        try {
            eventType = todolistXml.next();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return todoItems;
}


public class MyAdapter extends ArrayAdapter<name_price> {
    name_price[] items;

    public MyAdapter(Context context, int textViewResourceId,
            name_price[] objects) {
        super(context, textViewResourceId, objects);
        this.items = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = getLayoutInflater();
        View row = inflater.inflate(R.layout.list_raw_resevation, parent, false);

        TextView name,price;

        CheckBox ckbx = (CheckBox) row.findViewById(R.id.UpdateCheckBox);

        ckbx.setChecked(mainListView.isItemChecked(position));

        name = (TextView) row.findViewById(R.id.res_name);
        name.setText(items[position]._name);
        price = (TextView) row.findViewById(R.id.res_price);
        price.setText(Integer.toString(items[position]._price));

        return row;
    }

    public name_price getItem(int position) {
        return items[position];
    }

}
}


class name_price {
public String _name;
public int _price;
public int _id;
public CheckBox ckbx;

public name_price(int id, String name, int price)
{
    this._id=id;
    this._name = name;
    this._price = price;
}

public name_price() {
    // TODO Auto-generated constructor stub
}

}


我想我应该根据this更改mainListView.setOnItemClickListener中特定复选框的选中状态,但是我找不到解决方法。

另外,这是原始布局和列表布局(供其他使用):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">

<LinearLayout
    android:layout_width="0dip"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/res_name"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:gravity="center|left"
        android:singleLine="true"
        android:text="lalalalalalalalalallaallllaaaa"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/res_price"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_marginRight="10dp"
        android:gravity="center"
        android:text="90"
        android:textColor="#ffffff"
        android:textSize="15dp" />
</LinearLayout>

<CheckBox android:text=""
          android:id="@+id/UpdateCheckBox"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:focusable="false"  />
</LinearLayout>


列表布局:

<!--?xml version="1.0" encoding="utf-8"?-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="#81BEF7"
    android:scrollbars="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/Buttonlayout" android:orientation="horizontal"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:height="32dp" android:gravity="left|top" android:background="#2B60DE"
    android:paddingTop="2dp" android:paddingBottom="2dp">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/Buttonlayout2" android:orientation="horizontal"
    android:layout_height="wrap_content" android:gravity="left|center_vertical"
    android:layout_width="wrap_content" android:layout_gravity="left|center_vertical">


<TextView android:id="@+id/total_sum" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:textStyle="bold"
    android:textColor="#FFFFFF" android:text="@string/list_header"
    android:textSize="15sp" android:gravity="center_vertical"
    android:paddingLeft="5dp">
</TextView>
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/Buttonlayout22" android:orientation="horizontal"
    android:layout_height="wrap_content" android:gravity="right"
    android:layout_width="fill_parent" android:layout_gravity="right|center_vertical">

<Button android:id="@+id/btnSave" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="Send" android:textSize="15sp"
    android:layout_marginLeft="10px" android:layout_marginRight="10px"
    android:layout_marginBottom="2px" android:layout_marginTop="2px"
    android:height="15dp" android:width="70dp">
</Button>

<Button android:id="@+id/btnClear" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="Clear" android:textSize="15sp"
    android:layout_marginLeft="10px" android:layout_marginRight="10px"
    android:layout_marginBottom="2px" android:layout_marginTop="2px"
    android:height="15dp" android:width="70dp">
</Button>

</LinearLayout>
</LinearLayout>

<TableLayout android:id="@+id/TableLayout01" android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
<TableRow>
    <ListView android:id="@android:id/list" android:layout_width="wrap_content"
        android:textColor="#000000" android:layout_height="wrap_content">
    </ListView>
</TableRow>
</TableLayout>
</LinearLayout>


谢谢!
ÿ

最佳答案

早上好,我知道这应该可以解决您的问题:

public class Reservation_Activity extends ListActivity {
int total = 0;
private name_price[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
TextView total_tv;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_raw_resevation);

    total_tv = (TextView) findViewById(R.id.total_sum);
    Button btnSave = (Button) findViewById(R.id.btnSave);
    btnSave.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(getApplicationContext(),
                    " You clicked Save button", Toast.LENGTH_SHORT).show();

        }
    });

    Button btnClear = (Button) findViewById(R.id.btnClear);
    btnClear.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            total = 0;
            total_tv.setText("Pick and Send");
            Toast.makeText(getApplicationContext(),
                    " You clicked Clear button", Toast.LENGTH_SHORT).show();

            ClearSelections();
        }
    });

    // Prepare an ArrayList of todo items
    ArrayList<name_price> listTODO = PrepareListFromXml();
    this.mainListView = getListView();
    mainListView.setCacheColorHint(0);

    // Bind the data with the list
    lv_arr = (name_price[]) listTODO.toArray(lv_arr);

    mainListView.setAdapter(new MyAdapter(this,
            android.R.layout.simple_list_item_multiple_choice, lv_arr));

    mainListView.setItemsCanFocus(false);
    mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    mainListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            name_price item = (name_price) mainListView
                    .getItemAtPosition(position);

            if (mainListView.isItemChecked(position)) {
                total = total - item._price;
            } else {
                total += item._price;
            }
            mainListView.setItemChecked(position,
                    mainListView.isItemChecked(position));
            item.ckbx.setChecked(mainListView.isItemChecked(position));
            total_tv.setText("Total: " + total);
                }
            });
        }
        private void ClearSelections() {
            total = 0;
            int count = this.mainListView.getAdapter().getCount();
            for (int i = 0; i < count; i++) {
                this.mainListView.setItemChecked(i, false);
            }
        }
        private ArrayList<name_price> PrepareListFromXml() {
            ArrayList<name_price> todoItems = new ArrayList<name_price>();
            XmlResourceParser todolistXml = getResources().getXml(R.xml.order_items);
            int id = 0;
            int eventType = -1;
            while (eventType != XmlResourceParser.END_DOCUMENT) {
                if (eventType == XmlResourceParser.START_TAG) {
                    String strNode = todolistXml.getName();
                    if (strNode.equals("item")) {
                        todoItems.add(new name_price(id, todolistXml.getAttributeValue(null, "title"),Integer.parseInt(todolistXml.getAttributeValue(null,"price"))));
                        id++;
                    }
                }
                try {
                    eventType = todolistXml.next();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return todoItems;
        }
        public class MyAdapter extends ArrayAdapter<name_price> {
            name_price[] items;
            View row;
            CheckBox ckbx;
            public MyAdapter(Context context, int textViewResourceId,name_price[] objects) {
            super(context, textViewResourceId, objects);
            this.items = objects;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = getLayoutInflater();
            row = inflater.inflate(R.layout.reservation, parent, false);
            TextView name, price;
            ckbx = (CheckBox) row.findViewById(R.id.UpdateCheckBox);
            ckbx.setChecked(mainListView.isItemChecked(position));
            ckbx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    name_price item = (name_price) mainListView.getItemAtPosition(position);
                    if (ckbx.isChecked()) {
                        total = total - item._price;
                    } else {
                        total += item._price;
                    }
                    mainListView.setItemChecked(position,ckbx.isChecked());
                    total_tv.setText("Total: " + total);
                }
            });
            items[position].setCkbx(ckbx);
            name = (TextView) row.findViewById(R.id.res_name);
            name.setText(items[position]._name);
            price = (TextView) row.findViewById(R.id.res_price);
            price.setText(Integer.toString(items[position]._price));
            return row;
        }
        public name_price getItem(int position) {
            return items[position];
        }
    }
}


和:

class name_price {
public String _name;
public int _price;
public int _id;
public CheckBox ckbx;

public name_price(int id, String name, int price) {
    this._id = id;
    this._name = name;
    this._price = price;
}

public void setCkbx(CheckBox ckbx) {
    this.ckbx = ckbx;
}
}

关于android - 具有MyAdapter的ListView包含两个TextViews和CheckBox,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10816738/

10-09 00:00