如何从Android中的ListView获取已选中复选框的位置

时间:2016-02-16 09:46:20

标签: android listview checkbox

  

我在标题旁边创建了ListView个自定义CheckBox。我想接受检查   来自CheckBox

ListView      

我创建了以下函数,用于从ListView获取消息并使用ListView将其发送给另一个Intent,但我无法获得特定的CheckBox 位置搬家。

public class SpamActivity extends AppCompatActivity {

List<Message> sms;
ArrayList<Message> sms1;
ArrayList<String> al;
ListView lv;
CheckBox checkbox;

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

    lv= (ListView) findViewById(R.id.lvMsg);
    checkbox = (CheckBox) findViewById(R.id.checkBox);
     sms = new ArrayList<>();
     al=new ArrayList<>(0);
    populateMessageList();

  /*  SpamActivity spamactivity = new SpamActivity();
    al = spamactivity.al;
    //InboxFragment inboxfragment = new InboxFragment();
    //al = inboxfragment.list;

    for (int i=0;i<sms.size();i++){
        System.out.println("AddressSPS" + sms.get(i));
    }                */
    Collections.reverse(sms);

}

public void populateMessageList() {
     sms1 = new ArrayList<>();
    fetchDatabaseMessage();

    lv.setAdapter(new datalist(getApplicationContext(), sms1));

        // to handle click event on listView item
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
                // when user clicks on ListView Item , onItemClick is called
                // with position and View of the item which is clicked
                // we can use the position parameter to get index of clicked item
                TextView textViewSMSSender = (TextView) v.findViewById(R.id.lblNumber);
                TextView textViewSMSBody = (TextView) v.findViewById(R.id.lblMsg);
                TextView textViewSMSDate = (TextView) v.findViewById(R.id.smsdate);
                String smsSender = textViewSMSSender.getText().toString();
                String smsBody = textViewSMSBody.getText().toString();
                String smsDate = textViewSMSDate.getText().toString();

                Intent intentspam = new Intent(getApplicationContext(), DisplaySpamsms.class);
                intentspam.putExtra("number",smsSender);
                intentspam.putExtra("msg",smsBody);
                startActivity(intentspam);

            }
        });
}

// This method featch the message stored in database
public  void fetchDatabaseMessage(){
    DB_Message dbmessage = new DB_Message(this);
    sms = dbmessage.ViewMessageData();
    String addr = sms.get(0).getmAddress();
    if (addr.equals(sms.get(0).getmAddress())) {
        for (int i = 0; i < sms.size(); i++) {
            al.add(sms.get(i).getmAddress());
            //al.add(sms.get(i).getmBody());
        }
    }else {
        System.out.println("SMS Not Displayed");

    }
}


class datalist extends BaseAdapter {

    Context context;
    ArrayList<Message> arrayListsms;

    public datalist(Context context, ArrayList<Message> arrayListsms) {
        // TODO Auto-generated constructor stub
        this.context = context;
        this.arrayListsms = arrayListsms;
    }

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

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

    @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
        LayoutInflater inflator = getLayoutInflater();
        View row;
        row = inflator.inflate(R.layout.row, parent, false);
        //  ImageView img1 = (ImageView) row.findViewById(R.id.imageView1);
        final CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
        final TextView txt1 = (TextView) row.findViewById(R.id.lblMsg);
        final TextView txt2 = (TextView) row.findViewById(R.id.lblNumber);
        final TextView txt3 = (TextView) row.findViewById(R.id.smsdate);
        //Long timestamp = Long.parseLong(sms.get(position).getmDate());
        Calendar mcalendar = Calendar.getInstance();
        //mcalendar.setTimeInMillis(timestamp);
        DateFormat mformatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");


        txt1.setText(sms.get(position).getmBody());
        txt2.setText(sms.get(position).getmAddress());
        //+"\n"+mformatter.format(mcalendar.getTime())
        txt3.setText(mformatter.format(mcalendar.getTime()));

        final String msgBody = txt1.getText().toString();
        final String msgAddr = txt2.getText().toString();
        final String msgDate = txt3.getText().toString();

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Message msg = new Message();
                if (isChecked) {
                    //  selectedStrings.add(tv.getText().toString());

                    Toast.makeText(context, "" + msgBody, Toast.LENGTH_LONG).show();

                    System.out.println("Body" + msgBody);
                    System.out.println("Address" + msgAddr);
                    System.out.println("Date" + msgDate);

                      al.add(msgBody + msgAddr + msgDate);
                    //                        al.add(msgAddr);
                   //                        al.add(msgDate);

                    sms.remove(position);
                    ContentValues values = new ContentValues();
                    values.put("address", sms.get(position).getmAddress());
                    values.put("body", sms.get(position).getmBody());
                    String date = msg.getmDate();
                    SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
                    getContentResolver().insert(Uri.parse("content://sms/inbox"), values);

                    notifyDataSetChanged();
                } else {
                    //   selectedStrings.remove(tv.getText().toString());
                }

            }
        });


        return row;
    }
}

}
  

当我使用上述功能发送消息但错误是当我点击任何CheckBox发送该消息时,然后自动Different消息被发送到另一个活动。所以,我希望得到特定的message位置发送它。

2 个答案:

答案 0 :(得分:1)

您可以设置&#34; setOnItemClickListener&#34;在列表视图上并获得位置。

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

              // Here you can get the position   
          }
       });

答案 1 :(得分:0)

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;



public class SharedContactListAdapter extends ArrayAdapter<ContactSynResponse> {

    private Context context;
    private ViewHolder viewHolder;
    private SparseBooleanArray mSparseBooleanArray;
    private List<ContactSynResponse> mList;

    public SharedContactListAdapter(Context context, int resource,
            List<ContactSynResponse> objects) {
        super(context, resource, objects);
        this.context = context;
        mSparseBooleanArray = new SparseBooleanArray();
        // mList = objects;
    }

    @Override
    public ContactSynResponse getItem(int position) {
        return super.getItem(position);
    }

    public ArrayList<ContactSynResponse> getCheckedItems() {
        ArrayList<ContactSynResponse> mTempArry = new ArrayList<ContactSynResponse>();

        for (int i = 0; i < mList.size(); i++) {
            if (mSparseBooleanArray.get(i)) {

                ContactSynResponse data = mList.get(i);

                mTempArry.add(data);
            }
        }

        return mTempArry;
    }

    class ViewHolder {

        ImageView profilepic;
        ChimmerTextView contactname;
        ChimmerTextView contactno;
        RelativeLayout completelayout;
        CheckBox selectcheckbox;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater inflator = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflator.inflate(R.layout.sharedcontactlistdata,
                    parent, false);
            viewHolder = new ViewHolder();

            viewHolder.profilepic = (ImageView) convertView
                    .findViewById(R.id.profilepic_image_view);
            viewHolder.contactname = (ChimmerTextView) convertView
                    .findViewById(R.id.contactnameTV);
            viewHolder.contactno = (ChimmerTextView) convertView
                    .findViewById(R.id.contactnoTV);
            viewHolder.completelayout = (RelativeLayout) convertView
                    .findViewById(R.id.completeRL);
            viewHolder.selectcheckbox = (CheckBox) convertView
                    .findViewById(R.id.contact_checkbox);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        ContactSynResponse data = getItem(position);
        viewHolder.contactname.setText(data.getName());
        viewHolder.contactno.setText(data.getPhone());
        viewHolder.selectcheckbox.setTag(position);

        viewHolder.selectcheckbox.setOnCheckedChangeListener(new CheckListener(
                data, viewHolder.selectcheckbox));
        viewHolder.completelayout.setOnClickListener(new ClickListener(data,
                viewHolder.selectcheckbox));
        return convertView;
    }

    class CheckListener implements OnCheckedChangeListener {

        private CheckBox checkbox;

        public CheckListener(ContactSynResponse data, CheckBox checkbox) {

            this.checkbox = checkbox;

        }

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

            if (isChecked) {
                checkbox.setButtonDrawable(R.drawable.notification_selected_checkbox);

            } else {
                checkbox.setButtonDrawable(R.drawable.notification_checkbox);

            }
            buttonView.setChecked(isChecked);

            mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
        }

    }

    class ClickListener implements OnClickListener {
        private CheckBox checkbox;

        public ClickListener(ContactSynResponse data, CheckBox checkbox) {
            this.checkbox = checkbox;
        }

        @Override
        public void onClick(View v) {

            if (checkbox.isSelected()) {
                checkbox.setChecked(false);
                checkbox.setButtonDrawable(R.drawable.notification_checkbox);

                mSparseBooleanArray.put((Integer) checkbox.getTag(), false);
            } else {
                checkbox.setChecked(true);
                checkbox.setButtonDrawable(R.drawable.notification_selected_checkbox);
                mSparseBooleanArray.put((Integer) checkbox.getTag(), true);
            }

        }

    }

}