通过列表视图中的复选框获取所选项目以及数量编号选择器

时间:2016-06-29 02:54:26

标签: android listview

我正在创建一个应用程序,允许用户选择他们想要的食物并显示订购的食物。

我的列表视图有一个复选框,3个textview和一个数字选择器。我现在正尝试从numberpicker获取所选项目和数量,并显示在下一个活动上。我尝试了一些代码,但不确定它是否有效。

我对android studio有点新意。从现在开始我应该如何处理它?以下是我的代码

Listview行:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView1"
    android:id="@+id/txt1"
    android:textStyle="bold"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    style="bold" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView2"
    android:id="@+id/txt2"
    android:textStyle="bold"
    android:layout_below="@+id/txt1"
    android:layout_alignStart="@+id/txt1" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView3"
    android:id="@+id/txt3"
    android:textStyle="bold"
    android:layout_below="@+id/txt2"
    android:layout_alignStart="@+id/txt2" />

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ckBox"
    android:checked="false"
    android:layout_below="@+id/txt3"
    android:layout_alignStart="@+id/txt3" />

<ImageView

    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"

    android:scaleType="fitXY"
    android:gravity="left"
    android:layout_alignBottom="@+id/ckBox"
    android:layout_toStartOf="@+id/txt1"
    android:layout_alignParentEnd="false"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true" />

<NumberPicker
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/numberPicker"
    android:layout_toEndOf="@+id/txt2"
    android:layout_marginStart="23dp"
    android:layout_alignParentTop="true"
    android:layout_alignBottom="@+id/ckBox" />

customadapter:

public class CustomLVAdapter extends BaseAdapter {

private Context context;
LayoutInflater inflater;
private ArrayList<CustomItem> objectList;
private int[] imageId;

private class ViewHolder {
    TextView txt1,txt2,txt3;
    CheckBox ckBox;
    ImageView image;

    NumberPicker np;
}

public CustomLVAdapter(Context context, ArrayList<CustomItem> objectList,int[]prgmImages){
    this.context = context;
    this.inflater = LayoutInflater.from(context);
    this.objectList = objectList;
    this.imageId = prgmImages;


}

public int getCount(){
    return objectList.size();
}

public CustomItem getItem (int position) {
    return objectList.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;


    if (convertView == null) {
        holder = new ViewHolder();
        convertView = inflater.inflate(R.layout.row_checkbox_textview, null);
        holder.txt1 = (TextView) convertView.findViewById(R.id.txt1);
        holder.txt2 = (TextView) convertView.findViewById(R.id.txt2);
        holder.txt3 = (TextView) convertView.findViewById(R.id.txt3);
        holder.image=(ImageView) convertView.findViewById(R.id.image);
        holder.ckBox = (CheckBox) convertView.findViewById(R.id.ckBox);
        holder.np  = (NumberPicker) convertView.findViewById(R.id.numberPicker);
        holder.np.setMinValue(0);
        holder.np.setMaxValue(10);





        convertView.setTag(holder);

        holder.ckBox.setOnClickListener(new View.OnClickListener() {
                                            public void onClick(View v) {
                                                CheckBox cb = (CheckBox) v;
                                                CustomItem object = (CustomItem) cb.getTag();
                                                Toast.makeText(context,
                                                        "You have selected:  " + object.getItem() +
                                                                "Price: " + object.getPrice() +
                                                                "Qty: " + object.getQty(),
                                                        Toast.LENGTH_LONG).show();
                                                object.setSelected(cb.isChecked());
                                            }
                                        }
        );

        holder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                NumberPicker p = picker;
                CustomItem object = (CustomItem) p.getTag();
                object.setQty(String.valueOf(newVal));
            }
        });
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    CustomItem object = objectList.get(position);
    holder.txt1.setText(object.getItem());
    holder.txt2.setText(object.getDesc());
    holder.txt3.setText(object.getPrice());

    holder.np.setTag(object);
    holder.image.setImageResource(imageId[position]);
    holder.ckBox.setChecked(object.isSelected());
    holder.ckBox.setTag(object);

    return convertView;
} }

菜单活动:

public class MenuActivity extends Activity {


private String server = "http://172.16.156.56";
private String sql_table = "orders";
private ListView list;
private TextView txtOrder, txtMember, txtPrice;
private Button btnAdd;
ArrayList<String> rows;

ListView listView1;
Button btnSubmit;
ArrayList<CustomItem> itemList, selectedList;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);




    txtOrder=(TextView) findViewById(R.id.txt1);
    txtMember=(TextView) findViewById(R.id.txt2);
    txtPrice=(TextView) findViewById(R.id.txt3);

    list=(ListView) findViewById(R.id.listView);
    btnAdd = (Button)findViewById(R.id.button);


    rows = new ArrayList<String>();



    itemList=new ArrayList<CustomItem>();
    itemList.add(new CustomItem("Fried Rice","description","1","Quantity"));
    itemList.add(new CustomItem("Fried Noodle","description","2","Quantity"));
    itemList.add(new CustomItem("Prawn noodle","description","3","Quantity"));
    itemList.add(new CustomItem("Chicken Rice","description","4","Quantity"));

    int[] prgmImages={R.drawable.friedrice,R.drawable.friednoodle,R.drawable.pnoodle,R.drawable.chickenrice};

    listView1 = (ListView) findViewById(R.id.listView);
    CustomLVAdapter customLVAdapter = new CustomLVAdapter(this, itemList,prgmImages);
    listView1.setAdapter(customLVAdapter);




    btnSubmit = (Button) findViewById(R.id.button);
    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {



            StringBuffer responseText = new StringBuffer();
            selectedList = new ArrayList<CustomItem>();
            int total = 0;
            for (int i = 0; i < itemList.size(); i++) {
                CustomItem object = itemList.get(i);
                if (object.isSelected()) {
                    responseText.append(object.getItem() + "," + object.getQty() + ",");//item
                    selectedList.add(object);
                    //calculate price
                    total = total + Integer.parseInt(object.getQty()) * Integer.parseInt(object.getPrice());

                }
            }
            Add(responseText.toString(), "5565", String.valueOf(total));

            String strOrder = txtOrder.getText().toString();
            String strMember = txtMember.getText().toString();
            String strPrice = txtPrice.getText().toString();



            Intent i = new Intent(v.getContext(), ReceiptActivity.class);
            startActivity(i);

            i.putExtra("Order", strOrder);
            i.putExtra("Member", strMember);
            i.putExtra("Price", strPrice);

            Toast.makeText(getApplicationContext(), responseText + " $" + total,
                    Toast.LENGTH_SHORT).show();

            SelectAll();
            //store in database

            //go to ReceiptActivity - membership, item, totalprice

        }
    });


}



public void Add(final String item, final String membership, final String price)
{
    RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
    String url = server + "/insertorder.php";
    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    }) {
        protected Map<String, String> getParams() {
            Map<String, String> MyData = new HashMap<String, String>();
            MyData.put("item",item );
            MyData.put("membership",membership );
            MyData.put("price",price );

            return MyData;
        }
    };
    MyRequestQueue.add(MyStringRequest);
    SelectAll();
}
public void SelectAll()
{
    RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
    String url = server + "/fetchorder.php";
    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);
                JSONArray jsonMainNode = jsonResponse.optJSONArray(sql_table);
                rows.clear();
                for(int i=0; i < jsonMainNode.length(); i++)
                {
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                    String order       = jsonChildNode.optString("item").toString();
                    String membership     = jsonChildNode.optString("membership").toString();
                    String price = jsonChildNode.optString("price").toString();

                    rows.add(order + ", " + membership + ", " + price );
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(MenuActivity.this,
                        android.R.layout.simple_list_item_1, rows);
                list.setAdapter(adapter);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
        @Override
        public void onErrorResponse(VolleyError error) {
            //This code is executed if there is an error.
        }
    });
    MyRequestQueue.add(MyStringRequest);
}

}

收到活动(此处将显示所选项目的代码):

public class ReceiptActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_receipt);

    Bundle extras = getIntent().getExtras();
    String strOrder = extras.getString("Order");
    String strMember = extras.getString("Member");
    String strPrice = extras.getString("Price");

    TextView textView = (TextView)findViewById(R.id.textView);
    textView.setText("Order:" +strOrder+" ");

}

}

收据xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/background2"
tools:context="com.example.android.cardemulation.ReceiptActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/txt4"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentStart="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/txt5"
    android:layout_below="@+id/txt4"
    android:layout_centerHorizontal="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentStart="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="74dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textView2"
    android:layout_below="@+id/textView"
    android:layout_centerHorizontal="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textView3"
    android:layout_below="@+id/textView2"
    android:layout_centerHorizontal="true" />

CustomItem

public class CustomItem {
private  int id;
private  String item;
private  String price;
private  String desc;
private String qty;
private  Boolean selected = false;

public CustomItem(){

}


public CustomItem(String item,String desc, String price,String qty){
    this.item=item;
    this.desc=desc ;
    this.price=price;
    this.qty=qty;
}

public CustomItem(int id, String item,String desc, String price,String qty){
    this.id=id;
    this.item=item;
    this.desc=desc;
    this.price=price;
    this.qty=qty;
}

public int getId(){
    return id;
}

public void setId (int id) {
    this.id=id;
}

public String getItem(){
    return item;
}

public void setItem(String item){
    this.item=item;
}


public String getDesc()
{
    return desc;
}


public void setDesc(String desc) {
    this.desc=desc;
}



public String getPrice()
{
    return price;
}


public void setPrice(String price) {
    this.price=price;
}


public String getQty()
{
    return qty;
}


public void setQty(String qty) {
    this.qty=qty;
}





public boolean isSelected(){
    return selected;
}

public void setSelected(boolean selected){
    this.selected=selected;
}

}

1 个答案:

答案 0 :(得分:0)

我假设您的CustomItem类有一个布尔变量,其值可以通过getSelected()方法检索。
在Adapter类

中创建一个这样的公共静态ArrayList
public static ArrayList<CustomItem> arl_food=new ArrayList<>();

在CustomLVAdapter()构造函数中添加此

this.objectList=objectList;
arl_food.clear();
for(int i=0;i<this.objectList.size();i++)
{
    arl_food.add(this.objectList.get(i));
}

您应该将数据保存到ArrayList中的特定对象,而不是创建新的CustomItem对象。 在CheckBox点击事件中添加此代码:

arl_food.get(position).setSelected(cb.isChecked());

然后在NumberPicker valueChanged事件中:

arl_food.get(position).setQty(String.valueOf(newVal));

在“下一个活动”中,使用此列表:

for(int i=0;i<CustomLVAdapter.arl_food.size();i++)
{
    if(CustomLVAdapter.arl_food.get(i).getSelected())
    {
    //Show the food item from your list and do your stuff here
    }
}