I am currently implementing a multi-select ListView for my android app. My aim is to retrieve the selected items from the ArrayAdapter associated with the ListView when clicking the search button.
I am currently stumped on how to do this, I have found stuff online such as trying to set a MultiChoiceModeListener, but this does not seem to come up as an option in Eclipse. I am using Google APIs(level 10), Android 2.3.3 equivalent. Here is the code I have so far:
public class FindPlace extends Activity {
public FindPlace() {}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_places);
Button search = (Button) findViewById(R.id.search);
String[] categories = getResources().getStringArray(R.array.Categories);
ArrayAdapter ad = new ArrayAdapter(this,android.R.layout.simple_list_item_multiple_choice,categories);
final ListView list=(ListView)findViewById(R.id.List);
list.setAdapter(ad);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { }
});
}
}
Slightly more efficiently / correctly:
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < checked.size(); ++i)
{
if (checked.valueAt(i))
{
int pos = checked.keyAt(i);
doSomethingWith(adapter.getItem(pos));
}
}
Use the method getCheckedItemPosition().
take the count of the selected item in the int and make for loop like below.
int len = listView.getCount();
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < len; i++){
if (checked.get(i)) {
String item = cont_list.get(i);
/* do whatever you want with the checked item */
}
}
Related
I am a noob android studio and this is my first app I am developing.
Context: I have a ListView lv which is populated with CheckedTextViews using a ListAdapter.
ListAdapter adapter = new SimpleAdapter(
c, manageTrackers.trackers,
R.layout.list_item, new String[]{"id", "mobile", "status"},
new int[]{R.id.trackerID, R.id.trackerMobile, R.id.trackerStatus});
lv.setAdapter(adapter);
I have set up the OnItemClickListener for lv as shown below which checks and unchecks the check boxes as expected. I want the checks to remain persistent when I navigate between activities, so I am storing a key in the selectedTrackers array list.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.trackerID);
HashMap s = (HashMap)lv.getItemAtPosition(i);
String mob = (String)s.get("mobile");
//checked and pressed
if (ctv.isChecked())
{
ctv.setChecked(false);
for (int j = 0; j < selectedTrackers.size(); j++)
{
if (selectedTrackers.get(j) == mob)
{
selectedTrackers.remove(j);
break;
}
}
}
//not checked
else
{
ctv.setChecked(true);
selectedTrackers.add(mob);
}
}
});
When I navigate back to the activity with the list view, I call a function getSelectedTrackers which I want to select the saved checkboxes based on the key in selectedTrackers
public static void getSelectedTrackers()
{
if (basicSettings.selectedTrackers.size() == 0) return;
for (int i = 0; i < trackers.size(); i++)
{
HashMap s = trackers.get(i);
String mob = (String)s.get("mobile");
for (int j = 0; j < basicSettings.selectedTrackers.size(); j++)
{
if (basicSettings.selectedTrackers.get(j).equals(mob))
{
View v = getViewByPosition(i, lv);
CheckedTextView ctv = (CheckedTextView) v.findViewById(R.id.trackerID);
ctv.setChecked(true);
//******************************
//some call to update the view HERE
//******************************
break;
}
}
}
}
Question: I have confirmed that the function finds the correct checkbox, but none of the check boxes are displayed as being selected after calling setChecked(). I have scoured SO and tried invalidating, refreshing drawable state, notifyDataSetChanged, and I can't seem to figure it out how to get it to work. What's the best way to do this? Any help is appreciated!
In my home activity. I have listview with id list and textview with id count.
Here's the code:
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int count = 0;
for (int i = 0; i <= list.getLastVisiblePosition(); i++) {
if (list.getChildAt(i) != null) {
count++;
counter.setText(count + "");
}
}
I want to display in textview of rows in listview
Do you want to display how many items is in ListView or visible on screen?
For first option:
If you use ListView, then you have to use some ListAdapter (for example descendant of BaseAdapter or ArrayAdapter) which has method
getCount()
This returns, how many items is in adapter and also in ListView.
edit:
TextView countTextView; // here you want to set number of items
ListView lv; // your ListView
BaseAdapter adapter; // your adapter, that is used with ListView
// call this method in some listener
private void showNumberOfItems() {
int count = adapter.getCount();
countTextView.setText(String.valueOf(count));
}
You can use getLastVisiblePosition() method to count the number of rows,
int count=0;
for(int i = 0; i <= list.getLastVisiblePosition(); i++)
{
if(list.getChildAt(i)!= null)
{
count++; // saying that view that counts is the one that is not null, because sometimes you have partially visible items....
}
}
and then set the Text,
counter.setText(count + "");
Edit-
try something like this,
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int count = 0;
for (int i = 0; i <= list.getLastVisiblePosition(); i++) {
if (list.getChildAt(i) != null) {
count++;
}
}
counter.setText(count + "");
I am trying to find out the total number of selected rows in a customized list-view. If the number of items (rows) more than 2 then we cannot click the list-view again.Here I am using customized checklist(Multiple Choice)
What's wrong with listView.getCheckedItemCount()?
lvMain.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id)
{
int len = lvMain.getCount();
SparseBooleanArray checked = lvMain.getCheckedItemPositions();
for (int i = 1; i < len; i++){
if (checked.get(i)) {
count++;
/* do whatever you want with the checked item */
}
}
if(count>2)
{
/* do whatever you want with the checked item count more than one x value*/
lvMain.setSelected(false);
count=1;
}
}
});
Else, you could try to store your checkboxes and the other element displayed in a row (I've used TextView in my example) in a HashMap when overridden getView method get called and then count how many elements are checked iterating over the Map :
Iterator<Entry<TextView, CheckBox>> it = listCheck.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Entry<TextView, CheckBox> entry = it.next();
if (entry.getValue().isChecked())
i++;
}
return i;
I think you are trying to count the total number of selected rows in multiple listView.
for(i=0; listCount; i++) {
if(mListView.isItemChecked(i)){
}
else {
}
}
I am trying to make a listview with checkbox using listview's built in checkbox method. I have gone through a stackoverflow post and i found it is running properly except one problem.
If there are four items in list and assume, i checked the second and third item, onclicking, it is displaying the second and third item as needed..but if i am selecting first and then third and then second item, and then i m unchecking the first, so i must be left with second and third as desired output. But it is providing first second and third item as output.
can anybody guide me on that..?
This is the java code:
public class TailoredtwoActivity extends Activity implements OnItemClickListener, OnClickListener{
Button btn1;
ListView mListView;
String[] array = new String[] {"Ham", "Turkey", "Bread"};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tailoredtwo);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);
mListView = (ListView) findViewById(R.id.listViewcity);
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.btn_tailortwo_submit);
button.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
int size = positions.size();
for(int index = 0; index < size; index++) {
Toast.makeText(getApplicationContext(), array[positions.keyAt(index)].toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Change your onClick to
Delcare the below as a class variable
StringBuilder builder;
Then
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
builder = new StringBuilder();
for(int index = 0; index <array.length; index++) {
if(positions.get(index)==true)
{
builder.append(array[index]);
builder.append("\n");
}
}
Toast.makeText(getApplicationContext(),builder, Toast.LENGTH_LONG).show();
}
I am using android.R.layout.simple_list_item_checked for a listview in my application. but i'm unable to select a list item as checked.
here is the code
ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(Selectfarmer.this, android.R.layout.simple_list_item_checked,arraylistfarmer);
lvselectfarmer.setAdapter(arrayadapter);
I have found it, you need to use
lvselectfarmer.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
Try the following code,
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice,arraylistfarmer);
lvselectfarmer.setAdapter(arrayadapter);
int len = lvselectfarmer.getCount();
SparseBooleanArray checked = lvselectfarmer.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = lvselectfarmer.get(i);
/* do whatever you want with the checked item */
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
CheckedTextView textview = (CheckedTextView)v;
textview.setChecked(!textview.isChecked());
}