简体   繁体   English

使用Android中的复选框在列表视图中显示吐司消息

[英]using checkbox in android for displaying toast message in listview

What i have done ::I have got s list of items from server & display in listview each row of list has a checkbox in it, list view also has a button on top as show in figure below 我做了什么 ::我从服务器获得了项目列表并在列表视图中显示列表的每一行中都有一个复选框,列表视图的顶部也有一个按钮,如下图所示


在此处输入图片说明


What i need to do :: 我需要做什么 ::

  1. out of six rows if i select three rows using checkbox on click of button next showed in figure i must be able to display the toast message of selected elements 出六行的,如果我选择使用上点击按钮复选框三行next图显示我必须能够显示所选元素的吐司消息
  2. I don't know how to fill the parts of onclick function of checkButtonClick() in code 我不知道如何在代码中填充checkButtonClick()onclick函数的各个部分

ListViewAdapterForAtomicListItemtype.java 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 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 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 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) {





            }
        });

    }
}

{EDIT} {编辑}

BLD_IndividualListOfItems_Starters.java 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 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);    

    }
}

you can also use for MULTIPLE CHOICE OF LISTVIEW . 您还可以将其用于LISTVIEW的多选

StringBuilder result;

After Click on Button you can do this: 单击按钮后,您可以执行以下操作:

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);
        }
    });

And in your DisplayActivity you can do like this: 在您的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));

}

} }

Use a SparseBooleanArray . 使用SparseBooleanArray

More info @ 更多信息 @

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

In your adapter implement CompoundButton.OnCheckedChangeListener 在您的适配器中实现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()); 
    }

Then in getView 然后在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);

Override the following methods 覆盖以下方法

    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);    

}

In onClick of Button 在按钮的onClick中

   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();

Note: 注意:

It is better to use a ViewHolder Pattern. 最好使用ViewHolder模式。

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

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();

I think this wat you need. 我认为您需要这个水。 Just update you got solution or not. 只需更新您的解决方案即可。 this code must be in the next button onclickListener. 此代码必须位于onclickListener的下一个按钮中。 Try it out nd vote and ping if works. 尝试一下并投票,如果可行,请ping。 before tat update wats happening. 在tat更新发生之前。

ADDED: 添加:

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

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

This code is to check which item is clicked. 此代码用于检查单击了哪个项目。 by this with lenght of the list , check in for loop to check whether its checkbox is clicked or not. 通过列表的长度,检查循环以检查其复选框是否被单击。

Aftert that you can easily append that list of checked items. 之后,您可以轻松地添加已检查项目的列表。

Never tried but should work..you can use following code inside onClick() to get CheckBox status for each row. 从未尝试过,但应该可以..您可以在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
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM