使用android中的复选框在listview中显示toast信息

时间:2013-12-31 10:11:47

标签: java android android-listview android-checkbox

我做了什么 ::我有来自服务器&amp ;;的项目列表在listview中显示 每行列表中都有一个复选框,列表视图顶部还有一个按钮,如下图所示


enter image description here


我需要做什么 ::

    如果我使用复选框选择三行,则在六行中
  1. 按钮next如图所示我必须能够显示吐司 所选元素的消息
  2. 我不知道如何填写onclick函数的部分 代码中的checkButtonClick()

  3. ListViewAdapterForAtomicListItemtype.java

    public class ListViewAdapterForAtomicListItemtype extends BaseAdapter {
    
        // Declare Variables
        Context context;
        LayoutInflater inflater;
        ArrayList<HashMap<String, String>> data;
        HashMap<String, String> resultp = new HashMap<String, String>();
    
        public ListViewAdapterForAtomicListItemtype(Context context,
                ArrayList<HashMap<String, String>> arraylist) {
            this.context = context;
            data = arraylist;
        }
    
        @Override
        public int getCount() {
            return data.size();
        }
    
        @Override
        public Object getItem(int position) {
            return null;
        }
    
        @Override
        public long getItemId(int position) {
            return 0;
        }
    
        public View getView(final int position, View convertView, ViewGroup parent) {
            // Declare Variables
            TextView name;
    
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
            View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
            // Get the position
            resultp = data.get(position);
    
            // Locate the TextViews in listview_item.xml
            name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
    
            // Capture position and set results to the TextViews
            name.setText(resultp.get(MainActivity.NAME));
    
    
            return itemView;
        }
    }
    

    listview_main_atomic_list_itemtype.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    
        <ListView
            android:id="@+id/listview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_below="@+id/button1" />
    
        <Button
            android:id="@+id/button_of_listview_main_atomic_list_itemtype_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="DisplayItems" />
    
    </RelativeLayout>
    

    listview_item_for_atomic_list_item_type.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <TextView
            android:id="@+id/textView_id_atomic_list_item_type"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="17dp"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
        <CheckBox
            android:id="@+id/checkBox_atomic_list_item_type_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true" />
    
    </RelativeLayout>
    

    BLD_IndividualListOfItems_Starters.java

    public class BLD_IndividualListOfItems_Starters extends Activity{
        // Declare Variables
        JSONObject jsonobject;
        JSONArray jsonarray;
        ListView listview;
        ListViewAdapterForAtomicListItemtype adapter;
        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        static String NAME = "rank";
    
    
        String TYPE_FILTER;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xml
            setContentView(R.layout.listview_main_atomic_list_itemtype);
    
            TYPE_FILTER = getIntent().getExtras().getString("key_title");
            Log.v("---- Value-Start---", TYPE_FILTER);
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
    
            // Execute DownloadJSON AsyncTask
            new DownloadJSON().execute();
        }
    
        // DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<Void, Void, Void> {
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
                // Set progressdialog title
                //mProgressDialog.setTitle("Fetching the information");
                // Set progressdialog message
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            }
    
            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<HashMap<String, String>>();
    
                String newurl = "?" + "Key=" + TYPE_FILTER;
    
    
                // Retrieve JSON Objects from the given URL address
                jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
    
                try {
                    // Locate the array name in JSON
                    jsonarray = jsonobject.getJSONArray("restaurants");
    
                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put(MainActivity.NAME, jsonobject.getString("MasterListMenuName"));
    
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return null;
            }
    
            @Override
            protected void onPostExecute(Void args) {
                // Pass the results into ListViewAdapter.java
                adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
    
    
    
        private void checkButtonClick() {
    
    
            Button myButton = (Button) findViewById(R.id.button_of_listview_main_atomic_list_itemtype_id);
            myButton.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
    
    
    
    
                }
            });
    
        }
    }
    

    {编辑}

    BLD_IndividualListOfItems_Starters.java

    public class BLD_IndividualListOfItems_Starters extends Activity{
        // Declare Variables
        JSONObject jsonobject;
        JSONArray jsonarray;
        ListView listview;
        ListViewAdapterForAtomicListItemtype adapter;
        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        static String NAME = "rank";
    
    
        String TYPE_FILTER;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xml
            setContentView(R.layout.listview_main_atomic_list_itemtype);
    
            TYPE_FILTER = getIntent().getExtras().getString("key_title");
            Log.v("---- Value-Start---", TYPE_FILTER);
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
    
            // Execute DownloadJSON AsyncTask
            new DownloadJSON().execute();
        }
    
        // DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<Void, Void, Void> {
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
                // Set progressdialog title
                //mProgressDialog.setTitle("Fetching the information");
                // Set progressdialog message
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            }
    
            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<HashMap<String, String>>();
    
                String newurl = "?" + "Key=" + TYPE_FILTER;
    
    
                // Retrieve JSON Objects from the given URL address
                jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
    
                try {
                    // Locate the array name in JSON
                    jsonarray = jsonobject.getJSONArray("restaurants");
    
                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put(MainActivity.NAME, jsonobject.getString("MasterListMenuName"));
    
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return null;
            }
    
            @Override
            protected void onPostExecute(Void args) {
                // Pass the results into ListViewAdapter.java
                adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
    
    
    
        private void checkButtonClick() {
    
    
            Button myButton = (Button) findViewById(R.id.button_of_listview_main_atomic_list_itemtype_id);
            myButton.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
    
                    StringBuilder result = new StringBuilder();
                       for(int i=0;i<arraylist.size();i++)
                       {
                              if(adapter.mCheckStates.get(i)==true)
                              {
    
                                  result.append(arraylist.get(i).get(MainActivity.NAME));
                                  result.append("\n");
                              }
    
                        }
                        Toast.makeText(BLD_IndividualListOfItems_Starters.this, result, 1000).show();
    
    
                }
            });
    
        }
    }
    

    ListViewAdapterForAtomicListItemtype.java

    public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements android.widget.CompoundButton.OnCheckedChangeListener{
    
        // Declare Variables
        Context context;
        LayoutInflater inflater;
        ArrayList<HashMap<String, String>> data;
        HashMap<String, String> resultp = new HashMap<String, String>();
    
        SparseBooleanArray mCheckStates; 
    
        public ListViewAdapterForAtomicListItemtype(Context context,
                ArrayList<HashMap<String, String>> arraylist) {
            this.context = context;
            data = arraylist;
            mCheckStates = new SparseBooleanArray(data.size()); 
        }
    
        @Override
        public int getCount() {
            return data.size();
        }
    
        @Override
        public Object getItem(int position) {
            return null;
        }
    
        @Override
        public long getItemId(int position) {
            return 0;
        }
    
        public View getView(final int position, View convertView, ViewGroup parent) {
            // Declare Variables
            TextView name;
    
    
    
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
            View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
            // Get the position
    
            CheckBox chkSelect =(CheckBox) itemView.findViewById(R.id.checkBox_atomic_list_item_type_id);
    
            chkSelect.setTag(position);
            chkSelect.setChecked(mCheckStates.get(position, false));
            chkSelect.setOnCheckedChangeListener(this);
    
    
            resultp = data.get(position);
    
            // Locate the TextViews in listview_item.xml
            name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
    
            // Capture position and set results to the TextViews
            name.setText(resultp.get(MainActivity.NAME));
    
    
            return itemView;
        }
    
        public boolean isChecked(int position) {
            return mCheckStates.get(position, false);
        }
    
        public void setChecked(int position, boolean isChecked) {
            mCheckStates.put(position, isChecked);
    
        }
    
        public void toggle(int position) {
            setChecked(position, !isChecked(position));
    
        }
        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
    
            mCheckStates.put((Integer) buttonView.getTag(), isChecked);    
    
        }
    }
    

4 个答案:

答案 0 :(得分:1)

您还可以使用 多个LISTVIEW选择

StringBuilder result;

单击按钮后,您可以执行以下操作:

btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            result = new StringBuilder();
            for (int i = 0; i < arraylist.size(); i++) {
                if (adapter.mysparse.get(i) == true) {

                    result.append(arraylist.get(i).get(MainActivity.NAME));
                    result.append("\n");
                }

            }
            Intent n = new Intent(MainActivity.this, DisplayActivity.class);
            n.putExtra("buffer", result.toString());
            startActivity(n);
        }
    });

在您的 DisplayActivity 中,您可以这样做:

package com.example.singleitemlistview;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class DisplayActivity extends Activity {

ListView lv;
ArrayList<String> myList;
String myName;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);

    Intent n = getIntent();
    myName = n.getStringExtra("buffer");

    myList = new ArrayList<String>();

    lv = (ListView) findViewById(R.id.listViewData);

    myList.add(myName);

    lv.setAdapter(new ArrayAdapter<String>(DisplayActivity.this,
            android.R.layout.simple_list_item_1, myList));

}

}

答案 1 :(得分:1)

使用SparseBooleanArray

更多信息@

https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M

在您的适配器工具CompoundButton.OnCheckedChangeListener

public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{
SparseBooleanArray mCheckStates; 

 public ListViewAdapterForAtomicListItemtype(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
         mCheckStates = new SparseBooleanArray(data.size()); 
    }

然后在getView

   CheckBox chkSelect =(CheckBox) item.findViewById(R.id.CheckBox
    android:id="@+id/checkBox_atomic_list_item_type_id");

   chkSelect.setTag(position);
   chkSelect.setChecked(mCheckStates.get(position, false));
   chkSelect.setOnCheckedChangeListener(this);

覆盖以下方法

    public boolean isChecked(int position) {
        return mCheckStates.get(position, false);
    }

    public void setChecked(int position, boolean isChecked) {
        mCheckStates.put(position, isChecked);

    }

    public void toggle(int position) {
        setChecked(position, !isChecked(position));

    }
@Override
public void onCheckedChanged(CompoundButton buttonView,
        boolean isChecked) {

     mCheckStates.put((Integer) buttonView.getTag(), isChecked);    

}

onClick of Button

   StringBuilder result = new StringBuilder();
   for(int i=0;i<arraylist.size();i++)
   {
          if(adapter.mCheckStates.get(i)==true)
          {

              result.append(arrayList.get(i).get(MainActivtiy.Name));
              result.append("\n");
          }

    }
    Toast.makeText(ActivityName.this, result, 1000).show();

注意:

最好使用ViewHolder模式。

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

答案 2 :(得分:0)

StringBuffer result = new StringBuffer();
        result.append("TEXTVIEW 1  : ").append(chkbox1.isChecked());
        result.append("\nTEXTVIEW 2 : ").append(chkbox2.isChecked());
        result.append("\nTEXTVIEW 3 :").append(chkbox3.isChecked());

                //and so on.........

        Toast.makeText(MyAndroidAppActivity.this, result.toString(),
                Toast.LENGTH_LONG).show();

我认为你需要这个。只是更新你有解决方案。此代码必须位于onLlickListener的下一个按钮中。 尝试一下投票和ping如果有效。在更新之前发生的事情。

增加:

mainListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                String ss;
                ss=(String) ((TextView) view).getText();

此代码用于检查单击了哪个项目。 通过列表的长度,检查循环以检查是否单击了其复选框。

您可以轻松附加已检查项目列表。

答案 3 :(得分:0)

从未尝试但应该工作..您可以在onClick()中使用以下代码来获取每行的CheckBox状态。

    if (adapter!=null&&adapter.getCount()>0) {
        for(int i=0;i<adapter.getCount();i++){
            View view=(View)adapter.getItem(i);
            CheckBox chk=(CheckBox)view.findViewById(R.id.checkbox);
            TextView txt=(TextView)view.findViewById(R.id.textview);
            if (chk.isChecked()) {
                //do something here
            }
        }
    }