如何在listview中创建多选?

时间:2015-07-23 16:03:06

标签: android android-listview android-checkbox

我在我的Android应用程序中使用listview。我在列表视图中使用了一个复选框,我想知道:如何创建多选,如何通过按钮单击事件显示另一个活动中的所有选定项目。以下是代码段:

public class Home extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://api-11hr.anovatesoft.com/v1/list";

    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_CONTACT_NUMBER = "contactnumber";
    private static final String TAG_POSTAL_CODE = "postalcode";
    private static final String TAG_IMAGE = "image";
    SessionManager session;
    private double latitude;
    private double longitude;
    private String apikey;
    private String status;
    private  ImageView back;
    private  CheckBox check;

    GPSTracker gps;

    ListView listView;
    private Toolbar toolbar;                              // Declaring the Toolbar Object

    // contacts JSONArray
    JSONArray contacts = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        findViewsById();
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        check=(CheckBox)findViewById(R.id.ck);





        AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
                Home.this);

// Setting Dialog Title
        alertDialog2.setTitle("Too quiet?");

// Setting Dialog Message
        alertDialog2.setMessage("Follow your favourite merchants and see what deals they're launching at the 11th Hour!");



// Setting Positive "Yes" Btn
        alertDialog2.setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Write your code here to execute after dialog

                        dialog.cancel();

                    }
                });


        alertDialog2  .show();







        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {

                                    @Override
                                    public void onClick(View arg0) {
                                        Intent intent = new Intent(Home.this, ResultActivity.class);
                                        startActivity(intent);


                                    }
                                });



                Gps_func();
                // Session class instance
                session = new SessionManager(getApplicationContext());

                // get user data from session
                HashMap<String, String> user = session.getUserDetails();


                // apikey
                // Calling Application class (see application tag in AndroidManifest.xml)
                final GlobalClass globalVariable = (GlobalClass) getApplicationContext();

                //Set name and email in global/application context
                apikey = globalVariable.getApikey();


                latitude = globalVariable.getLatitude();
                longitude = globalVariable.getLongitude();
                status = globalVariable.getStatus();


                contactList = new ArrayList<HashMap<String, String>>();

                ListView lv = getListView();

                // Listview on item click listener
                lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        // getting values from selected ListItem

                        String cost = ((TextView) view.findViewById(R.id.email))
                                .getText().toString();


                        // Starting single contact activity
                        Intent in = new Intent(getApplicationContext(),
                                Adds.class);

                        in.putExtra(TAG_EMAIL, cost);

                        startActivity(in);

                    }
                });

                // Calling async task to get json
                new GetContacts().execute();
            }

            private void Gps_func() {

                gps = new GPSTracker(Home.this);

                // check if GPS enabled
                if (gps.canGetLocation()) {

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    //  Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                    Log.d("tag", "Longitude:\n" + longitude + "\n Latitude: \n" + latitude);

                } else {
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();

                    if (gps.canGetLocation()) {
                        double latitude = gps.getLatitude();
                        double longitude = gps.getLongitude();

                        // \n is for new line
                        // Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                        Log.d("tag", "Longitude:\n" + longitude + "\n Latitude: \n" + latitude);

                    }
                }

            }


            @Override
            protected void onRestart() {
                super.onRestart();
                Gps_func();
            }


            /**
             * Async task class to get json by making HTTP call
             */
            private class GetContacts extends AsyncTask<Void, Void, Void> {

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    // Showing progress dialog
                    pDialog = new ProgressDialog(Home.this);
                    pDialog.setMessage("Please wait....");
                    pDialog.setCancelable(false);
                    pDialog.show();

                }

                @Override
                protected Void doInBackground(Void... arg0) {
                    // Creating service handler class instance
                    ServiceHandler1 sh = new ServiceHandler1(apikey, latitude, longitude);


                    // Making a request to url and getting response
                    String jsonStr = sh.makeServiceCall(url, ServiceHandler1.POST);

                    Log.d("Response: ", "> " + jsonStr);


                    if (jsonStr != null) {
                        try {
                            JSONObject jsonObj = new JSONObject(jsonStr);

                            // Getting JSON Array node
                            contacts = jsonObj.getJSONArray(TAG_CONTACTS);

                            // looping through All Contacts
                            for (int i = 0; i < contacts.length(); i++) {
                                JSONObject c = contacts.getJSONObject(i);

                                String username = c.getString(TAG_USERNAME);
                                String name = c.getString(TAG_NAME);
                                String email = c.getString(TAG_EMAIL);
                                String address = c.getString(TAG_ADDRESS);
                                String gender = c.getString(TAG_CONTACT_NUMBER);
                                String postalcode = c.getString(TAG_POSTAL_CODE);


                                // tmp hashmap for single contact
                                HashMap<String, String> contact = new HashMap<String, String>();

                                // adding each child node to HashMap key => value

                                contact.put(TAG_EMAIL, email);


                                // adding contact to contact list
                                contactList.add(contact);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.e("ServiceHandler", "Couldn't get any data from the url");
                    }

                    return null;
                }


                @Override
                protected void onPostExecute(Void result) {
                    super.onPostExecute(result);
                    // Dismiss the progress dialog
                    if (pDialog.isShowing())
                        pDialog.dismiss();
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            Home.this, contactList,
                            R.layout.list_item1, new String[]{TAG_EMAIL,
                    }, new int[]{
                            R.id.email,});

                    setListAdapter(adapter);
                }

            }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.menu_main, menu);
                return true;
            }
    private void findViewsById() {
        check = (CheckBox) findViewById(R.id.ck);
        back = (ImageView) findViewById(R.id.back);
    }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                // Handle action bar item clicks here. The action bar will
                // automatically handle clicks on the Home/Up button, so long
                // as you specify a parent activity in AndroidManifest.xml.
                int id = item.getItemId();

                //noinspection SimplifiableIfStatement
                if (id == R.id.action_settings) {
                    return true;
                }

                return super.onOptionsItemSelected(item);
    }

3 个答案:

答案 0 :(得分:0)

这里我将为您提供简单的项目,可用于在列表视图中进行多项选择。

public class MainActivity extends Activity {

private ListView llChb;

private String[] data = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
        "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
        "x", "y", "z" };
private ArrayList<String> arrData=null;

private ArrayList<InfoRowdata> infodata;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    arrData=new ArrayList<String>();
    arrData.add("a");
    arrData.add("b");
    arrData.add("c");
    arrData.add("d");
    arrData.add("e");
    arrData.add("f");
    arrData.add("g");
    arrData.add("h");
    arrData.add("i");
    arrData.add("j");
    arrData.add("k");
    arrData.add("l");
    arrData.add("m");
    arrData.add("n");
    arrData.add("o");
    arrData.add("p");
    llChb = (ListView) findViewById(R.id.llChb);

    infodata = new ArrayList<InfoRowdata>();
    for (int i = 0; i < data.length; i++) {
        infodata.add(new InfoRowdata(false, i));
        // System.out.println(i);
        //System.out.println("Data is == "+data[i]);
    }
    llChb.invalidate();
    llChb.setAdapter(new MyAdapter());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public class MyAdapter extends BaseAdapter {

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View row = null;
        row = View.inflate(getApplicationContext(), R.layout.row, null);
        TextView tvContent=(TextView) row.findViewById(R.id.tvContent);
        //tvContent.setText(data[position]);
        tvContent.setText(data[position]);
        //System.out.println("The Text is here like.. == "+tvContent.getText().toString());

        final CheckBox cb = (CheckBox) row
                .findViewById(R.id.chbContent);
        cb.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (infodata.get(position).isclicked) {
                        infodata.get(position).isclicked = false;
                    } else {
                        infodata.get(position).isclicked = true;
                    }

                for(int i=0;i<infodata.size();i++)
                {
                    if (infodata.get(i).isclicked)
                    {
                        System.out.println("Selectes Are == "+ data[i]);
                    }
                }
            }
        });

        if (infodata.get(position).isclicked) {

            cb.setChecked(true);
        }
        else {
            cb.setChecked(false);
        }
        return row;
    }

} }

InfoRowdata课程在这里:

public class InfoRowdata {

public boolean isclicked=false;
public int index;
/*public String fanId;
public String strAmount;*/

public InfoRowdata(boolean isclicked,int index/*,String fanId,String strAmount*/)
{
    this.index=index;
    this.isclicked=isclicked;
    /*this.fanId=fanId;
    this.strAmount=strAmount;*/
} }

activity_main.xml here:

 <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"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/llChb"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</ListView>

row.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rlMain"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:id="@+id/rlInner"
        android:layout_width="fill_parent"
        android:layout_height="50dp" >

        <TextView
            android:id="@+id/tvContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp"
            android:text="Medium Text"
            android:textColor="#000000" />

        <CheckBox
            android:id="@+id/chbContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="10dp" />

    </RelativeLayout>

</RelativeLayout>

希望这对您有用:)

答案 1 :(得分:0)

最好的方法是使用API​​演示样本中提供的带有列表的ChoiceMode选项 - 你可以看看 https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/view/List11.javahttps://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/view/List15.java

First Refernce代码是

public class List11 extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice, GENRES));

        final ListView listView = getListView();
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    }
    private static final String[] GENRES = new String[] {
        "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
        "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
    };
}

您可以转到该链接并查看代码。

答案 2 :(得分:0)

您可以尝试MultiChoiceAdapter

enter image description here

MultiChoiceAdapter是ListAdapter的一种实现,它在原生Gmail应用程序中添加了对模态多项选择的支持。

它提供了类似于CHOICE_MODE_MULTIPLE_MODAL ListView模式的功能,还有两个额外的好处:

  • 它更易于使用,因为它会保留所选项目的数量,相应地更新其背景并透明地处理复选框。

  • 它与2.x版的每个Android版本兼容。当然,这意味着您的项目必须使用ActionBarSherlock或支持库ActionBarCompat