从自定义列表视图中获取选中的项ID并将其传递给新活动android

时间:2016-08-08 12:11:09

标签: android json listview checkbox bundle

我正在开发一个Android应用,它有一个带复选框的自定义列表视图。我想将所有已检查的项目从一个活动传递到另一个活动。我应该如何通过它们?我应该在哪里管理自定义适配器或活动中的复选框(以获取所有选中的项目)?

注意:我使用json响应从服务器检索所有数据。

这是我的模特:

  public class Groups {
        public String name;
        public boolean selected= false;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public boolean isSelected() {
            return selected;
        }

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

        public Groups() {
        }
    }

我的适配器:

public class AdapterMainActivity扩展了BaseAdapter {

Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;

public AdapterMainActivity(Activity activity, List<Groups> groupses) {
    this.activity = activity;
    this.groupsList = groupses;
}

@Override
public int getCount() {
    return groupsList.size();
}

@Override
public Object getItem(int position) {
    return groupsList.get(position);
}

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

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

    if (inflater == null) {
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.custom_list, null);
        TextView name = (TextView) convertView.findViewById(R.id.textViewName);
        final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);

        final Groups groups = groupsList.get(position);
        name.setText(groupsList.get(position).getName());

        checkBox.setChecked(groups.selected);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                groups.selected = isChecked;
                MainActivity.getInstance().updateArrayList(groupsList);
            }
        });


    }

    return convertView;
}

}

MainActivity:

public class MainActivity extends AppCompatActivity {

    ListView listViewGroups;
    Button buttonSentToActivity;

    List<Groups> groupsList;
    List<Groups> resultGroupList;
    ArrayList<Boolean> areChecked;
    List<String> finalArray;

    private AdapterMainActivity adapterMainActivity;

    static MainActivity yourActivity;

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

        yourActivity = this;

        groupsList= new ArrayList<Groups>();
        resultGroupList= new ArrayList<Groups>();

        ReadGroup(37);

        adapterMainActivity = new AdapterMainActivity(this, groupsList);

        listViewGroups = (ListView) findViewById(R.id.listViewGroups);
        listViewGroups.setAdapter(adapterMainActivity);

        buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
        buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);

        Log.e("Group list size ", String.valueOf(groupsList.size()));
        finalArray = new ArrayList<>();
        for (int i = 0; i < resultGroupList.size(); i++) {
            if (resultGroupList.get(i).selected) {
                finalArray.add(resultGroupList.get(i).getName());
                Log.e("final array size", String.valueOf(finalArray.size()));
            }
        }

    }
    public void ReadGroup(long cid) {
        Response.Listener<String> responseListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.toString());
                    JSONArray readArray = jsonObject.getJSONArray("groups");

                    for (int i = 0; i < readArray.length(); i++) {

                        Log.e("i is: ", String.valueOf(i));
                        JSONObject jssonRow = readArray.getJSONObject(i);

                        String groupName = jssonRow.getString("name");

                        Groups groups = new Groups();
                        groups.setName(groupName);
                        Log.e("NAME is: ", groupName);
                        groupsList.add(groups);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapterMainActivity.notifyDataSetChanged();
            }
        };

        Log.e("Client id is: ", String.valueOf(cid));
        ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        queue.add(readGroupRequest);

        Log.e("out of the loop", "");
    }

    public static MainActivity getInstance() {
        return yourActivity;
    }

    public void updateArrayList(List<Groups> arrayList) {
        this.resultGroupList = arrayList;
    }

    View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Bundle b= new Bundle();
            //b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
            //intent.putExtras(b);
            Log.e("final array size", String.valueOf(finalArray.size()));
            startActivity(intent);
        }
    };

}

2 个答案:

答案 0 :(得分:0)

首先,管理您的复选框:

在你的activity类中添加一个布尔数组或arraylist,其大小与列表数组大小相同,并在初始化时将所有值初始化为false:

String[] titlesArray;
ArrayList<Boolean> arrChecked;

// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
    arrChecked = new ArrayList<Boolean>();
    for (int i = 0; i < titles.size(); i++) {
    arrChecked.add(false);
    }

现在用以下代码替换你的适配器类:

class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();

ArrayList<Boolean> arrChecked;

VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {

super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;

}

class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;

MyViewHolder(View v) {
    myImage = (ImageView) v.findViewById(R.id.imageView1);
    myTitle = (TextView) v.findViewById(R.id.textView1);
    myDescription = (TextView) v.findViewById(R.id.textView2);
    box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
    // 1.ºtime
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    //row contem RelativeLayout(root) em single_row.xml
    row = inflater.inflate(R.layout.single_row, parent, false);
    holder = new MyViewHolder(row);
    row.setTag(holder);
    //Log.d("VIVZ", "Creating a new Row");
} else {
    //reciclamos aqui, qeremos usar antigo objecto holder
    holder = (MyViewHolder) row.getTag();
    //Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);

//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            int id = v.getId();

            if (arrChecked.get(id)) {
                //if checked, make it unchecked
                arrChecked.set(id, false);
            } else {
                //if unchecked, make it checked
                arrChecked.set(id, true);

            }

        }
    });

    //set the value of each checkbox from arrChecked boolean array
    holder.box.setChecked(arrChecked.get(position));

return row;
}
}

之后,实现发送按钮的点击监听器说btnSend按钮(我正在考虑您通过点击发送按钮将数据从一个活动发送到另一个活动):

 btnSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ArrayList<String> arrTempList = new ArrayList();
            for(int i=0; i<titles.size(); i++){
               if(arrChecked.get(i) == true){
                  arrTempList.add(titles[i]);
               }
            }

            // here you can send your arrTempList which is having checked items only

        }
    });

答案 1 :(得分:0)

以下是此问题的解决方案:

我的适配器:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.xxxx.release</groupId>
            <artifactId>xxxx-version</artifactId>
            <version>${project.version}</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

在我的活动中,我有按钮从1活动转到2活动:

public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;

public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
    this.activity = activity;
    this.contactsList = group;
}

@Override
public int getCount() {
    return contactsList.size();
}

@Override
public Object getItem(int position) {
    return contactsList.get(position);
}

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

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

    if (inflater == null) {
        inflater = (LayoutInflater)             activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    if (convertView == null) {

        convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
     null);

        final TextView fNAme = (TextView)   convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
        TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);

        checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);

        checkBoxAdapter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckBox cb = (CheckBox) view;
                Contacts contacts = (Contacts) cb.getTag();
                contacts.setSelected(cb.isChecked());

                Toast.makeText(activity.getApplicationContext(),
                        "Clicked on Checkbox: " + cb.getText() +
                                " is " + cb.isChecked(),
                        Toast.LENGTH_LONG).show();

            }
        });


        final Contacts contacts = contactsList.get(position);


        fNAme.setText(contacts.getContactFName());
        LName.setText(contacts.getContactLName());
        checkBoxAdapter.setChecked(contacts.isSelected());
        checkBoxAdapter.setTag(contacts);
    }
    return convertView;
    }
    }

第二个活动添加此代码:

    private View.OnClickListener buttonSubmitGroupListener =new      View.OnClickListener() {
    @Override
    public void onClick(View view) {
       List <Integer> contactsIDArray= new ArrayList<Integer>();
        List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
        for(int i=0; i< arrayOfContacts.size(); i++){
            Contacts contacts= arrayOfContacts.get(i);

            if(contacts.isSelected()==true){
                contactsIDArray.add(contacts.getContactID());
            }
        }

        for (int i = 0; i < contactsIDArray.size(); i++) {
            Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
            Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
        }

        intent = new Intent(getApplicationContext(), SendSMSActivity.class);
        Bundle b = new Bundle();
        b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
        intent.putExtras(b);
        startActivity(intent);
    }
};