Thomashaertel's library as a multi-select spinner - android

I have been using Thomashaertel's library as a multi-select spinner.
Unless I select all the items, there is no issue but when I select all
the items, It doesn't display the selected item in the textview.
I tried looking for the solution but failed.
Lemme know if anyone has resolved that issue.
This is how I am creating the list. Is there some issue with the way I am creating it or there is some issue with the Library itself??
spinner = new MultiSpinner(context);
adapter = ArrayAdapter.createFromResource(context,
R.array.data_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
I am getting the array from the String resource file.

Yeah, even I had the same problem a few weeks back. It seems to be an issue of the library. I had raised the issue on Github too but no response.
I don't have the solution for this one but have a hack.
Instead of using the multispinner's textview,
you can make use of regular textview and add onClickListener to it.
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner.callOnClick(); // call spinner's onClick when textview is clicked
}
This lets you render the dialog with multiselect options.
Now maintain a stringbuilder.
Set the adapter on the spinner and override onItemsSelected(boolean)
and follow the below code
public void onItemsSelected(boolean[] selected) {
stringbuilder = new StringBuilder();
for (int i = 0; i < adapter.getCount(); i++) {
if (selected[i]) {
list.add(String.valueOf(adapter.getItem(i).toString())); //get the list of selected items
if (stringbuilder.length() == 0) {
stringbuilder.append(adapter.getItem(i));
} else {
stringbuilder.append(",").append(adapter.getItem(i));
}
textView.setText(String.valueOf(stringbuilder));
} else {
list.remove(adapter.getItem(i).toString()));
}
}
if (stringbuilder.length() == 0) {
textView.setText(" Make your selection");
}
}
It looks clean compared to the view that multispinner gives and also you have to customize
advantage.
Hope it is useful

Related

Select multiple items from recycler view list delete not working Properly

if (RFidList.size() >0){
for (String s: RFidList){
RFidTagValueList.remove(s);
}
}
mTimeAdapter.notifyDataSetChanged();
dialog.dismiss();
when choose multiple items in recyclerview checkbox not working / and am use private ArrayList<String> data = new ArrayList<>();
You can't move and delete from the list. The best option to do this is to have an array that will remember the state of the checkbox. Scrolling through your recycler view will always change the state of the checkbox and maybe won't remember it. The way to do this is to add an array of boolean
private boolean[] checkStates;
then inside your constructor of the adapter do this.
checkStates = new boolean[data.size()];
This way you'll create an array of boolean filled with FALSE value the same size your data array is. Now, inside your adapter when you are binding your view do this for the checkbox.
holder.checkbox.setChecked(checkStates[position]);
Also, don't use onCheckedChangeListener on checkbox inside adapter. This will be called even when you scroll and it will change whatever you are doing inside the function. What you can do is override onClick for the checkbox, but there is something tricky here. When you click the checkbox to check it, inside the onClick method the view will have the state as it is already checked so to follow this do it like this:
holder.checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Checkbox c = (CheckBox) v;
checkStates[position] = c.isChecked();
}
});
I wrote this from my head and maybe there are some mistakes but you'll get the point. The animation of the check state will be handled you just need to handle changes inside the checkStates array.
Now your checkbox will always have the state it had before. After this, you can create a function to delete items from your data.
public void removeItems() {
ArrayList<YOUR-MODEL> items_to_delete = new ArrayList<>();
for (int i = 0; i < checkStates.length(); ++i) {
if (checkStates[i]) items_to_delete.add(data.get(i]);
}
data.removeAll(items_to_delete);
notifyDataSetChanged();
checkStates = new boolean[data.size()];
}
This works if your data is a type of ArrayList. I think this is the best way to go.

Listview two items selected while scrolling

I am facing issue in multiselect listview and issue i am facing was when i select the first item in the listview last item also checked while scrolling and this issue happens only if i have more that 10+ items in listview. I don't know what's wrong in my code and could any one suggest me a proper solution to avoid this problem.Thanks in advance
private class MultipleChoiceClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (questionCount > 0) {
ImageView imgTick = (ImageView) view.findViewById(R.id.imgTick);
int len = lvMultiSelect.getCount();
checked = lvMultiSelect.getCheckedItemPositions();
for (int i = 0; i < len; i++) {
if (i == position) {
if (checked.get(i)) {
lvMultiSelect.getChildAt(i).setBackgroundColor(
getResources().getColor(
R.color.listitem_onclick));
imgTick.setImageResource(R.drawable.tick_img);
} else {
lvMultiSelect.getChildAt(i).setBackgroundColor(
getResources().getColor(
R.color.default_list_background));
imgTick.setImageResource(R.drawable.not_checked_img);
}
}
}
}
Create an object to store the position of all tags something like Integer array.
In your onItemClick, try this:
checked = view.getTag();
and once you select an item, do view.setTag(positions);. But nevertheless I suggest you, switch to RecyclerView if this codebase is new / you are doing it from scratch.
I have done this using RecyclerView Multiselect using Contextual Action Mode. Check this.

Set selected item of spinner programmatically

I am working on an android project and I am using a spinner which uses an array adapter which is populated from the database.
I can't find out how I can set the selected item programmatically from the list. For example if, in the spinner I have the following items:
Category 1
Category 2
Category 3
How would I programmatically make Category 2 the selected item when the screen is created. I was thinking it might be similar to c# I.E Spinner.SelectedText = "Category 2" but there doesn't seem to be any method similar to this for Android.
Use the following:
spinnerObject.setSelection(INDEX_OF_CATEGORY2).
No one of these answers gave me the solution, only worked with this:
mySpinner.post(new Runnable() {
#Override
public void run() {
mySpinner.setSelection(position);
}
});
public static void selectSpinnerItemByValue(Spinner spnr, long value) {
SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
for (int position = 0; position < adapter.getCount(); position++) {
if(adapter.getItemId(position) == value) {
spnr.setSelection(position);
return;
}
}
}
You can use the above like:
selectSpinnerItemByValue(spinnerObject, desiredValue);
& of course you can also select by index directly like
spinnerObject.setSelection(index);
Some explanation (at least for Fragments - never tried with pure Activity). Hope it helps someone to understand Android better.
Most popular answer by Arun George is correct but don't work in some cases. The answer by Marco HC uses Runnable wich is a last resort due to additional CPU load. The answer is - you should simply choose correct place to call to setSelection(), for example it works for me:
#Override
public void onResume() {
super.onResume();
yourSpinner.setSelection(pos);
}
But it won't work in onCreateView(). I suspect that is the reason for the interest to this topic.
The secret is that with Android you can't do anything you want in any method - oops:( - components may just not be ready. As another example - you can't scroll ScrollView neither in onCreateView() nor in onResume() (see the answer here)
To find a value and select it:
private void selectValue(Spinner spinner, Object value) {
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).equals(value)) {
spinner.setSelection(i);
break;
}
}
}
Why don't you use your values from the DB and store them on an ArrayList and then just use:
yourSpinner.setSelection(yourArrayList.indexOf("Category 1"));
The optimal solution is:
public String[] items= new String[]{"item1","item2","item3"};
// here you can use array or list
ArrayAdapter adapter= new ArrayAdapter(Your_Context, R.layout.support_simple_spinner_dropdown_item, items);
final Spinner itemsSpinner= (Spinner) findViewById(R.id.itemSpinner);
itemsSpinner.setAdapter(adapter);
To get the position of the item automatically add the following statement
itemsSpinner.setSelection(itemsSpinner.getPosition("item2"));
You can make a generic method for this kind of work as I do in my UtilityClass which is
public void SetSpinnerSelection(Spinner spinner,String[] array,String text) {
for(int i=0;i<array.length;i++) {
if(array[i].equals(text)) {
spinner.setSelection(i);
}
}
}
You can easily set like this: spinner.setSelection(1), instead of 1, you can set any position of list you would like to show.
I have a SimpleCursorAdapter so I have to duplicate the data for use the respose in this post. So, I recommend you try this way:
for (int i = 0; i < spinnerRegion.getAdapter().getCount(); i++) {
if (spinnerRegion.getItemIdAtPosition(i) == Integer
.valueOf(signal.getInt(signal
.getColumnIndexOrThrow("id_region")))) {
spinnerRegion.setSelection(i);
break;
}
}
I think that is a real way
In Kotlin I found a simple solution using a lambda:
spinnerObjec.post {spinnerObjec.setSelection(yourIndex)}
This is what I use in Kotlin:
spinner.setSelection(resources.getStringArray(R.array.choices).indexOf("Choice 1"))
I know that is already answered, but simple code to select one item, very simple:
spGenre.setSelection( ( (ArrayAdapter) spGenre.getAdapter()).getPosition(client.getGenre()) );
This is work for me.
spinner.setSelection(spinner_adapter.getPosition(selected_value)+1);
This is stated in comments elsewhere on this page but thought it useful to pull it out into an answer:
When using an adapter, I've found that the spinnerObject.setSelection(INDEX_OF_CATEGORY2) needs to occur after the setAdapter call; otherwise, the first item is always the initial selection.
// spinner setup...
spinnerObject.setAdapter(myAdapter);
spinnerObject.setSelection(INDEX_OF_CATEGORY2);
This is confirmed by reviewing the AbsSpinner code for setAdapter.
If you have a list of contacts the you can go for this:
((Spinner) view.findViewById(R.id.mobile)).setSelection(spinnerContactPersonDesignationAdapter.getPosition(schoolContact.get(i).getCONT_DESIGNATION()));
for (int x = 0; x < spRaca.getAdapter().getCount(); x++) {
if (spRaca.getItemIdAtPosition(x) == reprodutor.getId()) {
spRaca.setSelection(x);
break;
}
}
Most of the time spinner.setSelection(i); //i is 0 to (size-1) of adapter's size
doesn't work. If you just call spinner.setSelection(i);
It depends on your logic.
If view is fully loaded and you want to call it from interface I suggest you to call
spinner.setAdapter(spinner_no_of_hospitals.getAdapter());
spinner.setSelection(i); // i is 0 or within adapter size
Or if you want to change between activity/fragment lifecycle, call like this
spinner.post(new Runnable() {
#Override public void run() {
spinner.setSelection(i);
}
});
Here is the Kotlin extension I am using:
fun Spinner.setItem(list: Array<CharSequence>, value: String) {
val index = list.indexOf(value)
this.post { this.setSelection(index) }
}
Usage:
spinnerPressure.setItem(resources.getTextArray(R.array.array_pressure), pressureUnit)
This Worked For me:
mySpinner.post(new Runnable() {
#Override
public void run() {
mySpinner.setSelection(position);
spinnerAdapter.notifyDataSetChanged();
}
});
Yes, you can achieve this by passing the index of the desired spinner item in the setSelection function of spinner. For example:
spinnerObject.setSelection(INDEX_OF_CATEGORY).
In my case, this code saved my day:
public static void selectSpinnerItemByValue(Spinner spnr, long value) {
SpinnerAdapter adapter = spnr.getAdapter();
for (int position = 0; position < adapter.getCount(); position++) {
if(adapter.getItemId(position) == value) {
spnr.setSelection(position);
return;
}
}
}
I had made some extension function of Spinner for loading data and tracking item selection.
Spinner.kt
fun <T> Spinner.load(context: Context, items: List<T>, item: T? = null) {
adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, items).apply {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
if (item != null && items.isNotEmpty()) setSelection(items.indexOf(item))
}
inline fun Spinner.onItemSelected(
crossinline itemSelected: (
parent: AdapterView<*>,
view: View,
position: Int,
id: Long
) -> Unit
) {
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
itemSelected.invoke(parent, view, position, id)
}
}
}
Usaage Example
val list = listOf("String 1", "String 2", "String 3")
val defaultData = "String 2"
// load data to spinner
your_spinner.load(context, list, defaultData)
// load data without default selection, it points to first item
your_spinner.load(context, list)
// for watching item selection
your_spinner.onItemSelected { parent, view, position, id ->
// do on item selection
}
This worked for me:
#Override
protected void onStart() {
super.onStart();
mySpinner.setSelection(position);
}
It's similar to #sberezin's solution but calling setSelection() in onStart().
I had the same issue since yesterday.Unfortunately the first item in the array list is shown by default in spinner widget.A turnaround would be to find the previous selected item with each element in the array list and swap its position with the first element.Here is the code.
OnResume()
{
int before_index = ShowLastSelectedElement();
if (isFound){
Collections.swap(yourArrayList,before_index,0);
}
adapter = new ArrayAdapter<String>(CurrentActivity.this,
android.R.layout.simple_spinner_item, yourArrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item; yourListView.setAdapter(adapter);
}
...
private int ShowLastSelectedElement() {
String strName = "";
int swap_index = 0;
for (int i=0;i<societies.size();i++){
strName = yourArrayList.get(i);
if (strName.trim().toLowerCase().equals(lastselectedelement.trim().toLowerCase())){
swap_index = i;
isFound = true;
}
}
return swap_index;
}

Set Value of spinner from Array in strings.xml

I have a spinner, that uses an array from strings.xml
if the array has 5 strings (1,2,3,4,5), and i want the spinner to show second
string (2) as default value, is this possible?
I know i can re-arrange the strings order so that first one is 2,
but this doesn't look very good if spinner dialog appears as (2,1,3,4,5).
Or does the array have to be created within my activity programatically
and then use setPostion()?
I have tried this, but get a fault when creating array in activity.
Can anyone please give me an example of how to create array and use
it in spinner()
I have also searched on here for answers but cant seem to find what i need.
Thanks for looking....
I recommend you check: http://developer.android.com/resources/tutorials/views/hello-spinner.html
You should create an ArrayAdapter in your Activity.
From the above link:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
You can use
spinner.setSelection(adapter.getPosition(value)));
to set the position.
Cheers for reply.....
Didn't do what i needed, but have managed to solve my problem as follows..
First i created an array within my activity, instead of strings.xml.
String[] NoCore_Array = new String [5];
{
NoCore_Array[0] = "1";
NoCore_Array[1] = "2";
NoCore_Array[2] = "3";
NoCore_Array[3] = "4";
NoCore_Array[4] = "5";
}
Then i created the spinner using...
Spinner spnNoCore = (Spinner) findViewById(R.id.spinner_nocore);
Then created the adapter, using above array....
ArrayAdapter NoCoreAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, NoCore_Array);
spnNoCore.setAdapter(NoCoreAdapter);
Then set default position of the adapter as follows...
//Set Default Selection
spnNoCore.setSelection(1);
Then rest of spinner code for actions...
spnNoCore.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//Get item from spinner and store in string conductorSize........
NoCore = parent.getItemAtPosition(pos).toString();
if (NoCore.equals(NoCore1)) { CoreNo = 1 ; }
if (NoCore.equals(NoCore2)) { CoreNo = 2 ; }
if (NoCore.equals(NoCore3)) { CoreNo = 3 ; }
if (NoCore.equals(NoCore4)) { CoreNo = 4 ; }
if (NoCore.equals(NoCore5)) { CoreNo = 5 ; }
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
Hope this may help other people who are having same problem with
setting default selection on Spinner.
However the layout of the dialog is not as good when done this way,
Radio buttons are missing, just looks like a text selection
with lines dividing the sections.

Why is ListView.getCheckedItemPositions() not returning correct values?

The app has a ListView with multiple-selection enabled, in the UI it works as expected. But when I read the values out using this code:
Log.i(TAG,"Entered SearchActivity.saveCategoryChoice()");
SparseBooleanArray checkedPositions = categorySelector.getCheckedItemPositions();
Log.i(TAG,"checkedPositions: " + checkedPositions.size());
if (checkedPositions != null) {
int count = categoriesAdapter.getCount();
for ( int i=0;i<count;i++) {
Log.i(TAG,"Selected items: " + checkedPositions.get(i));
}
}
I get this output, no matter what state each checkbox is in:
Entered SearchActivity.saveCategoryChoice()
checkedPositions: 0
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
Selected items: false
The SparseBooleanArray seems to return false for any non-existent item, so the source of the problems seems to be that getCheckedItemPositions() is returning an empty array. The method is behaving as if there are no items in the ListView, but there are.
I can see from the docs that no values are returned when the ListView is not set up as multi-select, but it is, using this statement:
categorySelector.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
In my scenario, the adapter I'm using is a subclass of ArrayAdapter, and (without any solid evidence) I suspect this may be the cause, though I can't see why it shouldn't work.
kcoppock is right, you need to use valueAt(), the working code should be
SparseBooleanArray checkedItems = categorySelector.getCheckedItemPositions();
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = categorySelector.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
Log.i(TAG,item + " was selected");
}
}
}
I remember having an issue with this myself a while back. Here is my previous question, which isn't directly related to your issue, but contains some code that may help. What you might want to try is using checkedPositions.valueAt(int index) rather than checkedPositions.get(int index). I think that may be what you're actually looking for.
I still do not know why, but in my scenario, getCheckedItemPositions() returns false values for all items. I cannot see a way to use the methods on the ListView to get the boolean values out. The SparseBooleanArray object seems to have no real-world data in it. I suspect this may be because of some quirk of my implementation, perhaps that I've subclassed ArrayAdapter. It's frustrating, issues like this are a real time-drain.
Anyway, the solution I have used is to to attach a handler to each Checkbox individually as ListView rows are created. So from ListView.getView() I call this method:
private void addClickHandlerToCheckBox(CheckBox checkbox) {
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
CheckBox checkbox = (CheckBox)arg0;
boolean isChecked = checkbox.isChecked();
// Store the boolean value somewhere durable
}
});
}
None of the above solutions have worked for me, instead I get every child (a checkedTextView) from the ListView and see if it is checked or not:
ListView myListView = myViewActivity.getListView();
ArrayList<String> selectedChildren2 = new ArrayList<String>();
for(int i = 0;i<myListView.getChildCount();i++)
{
CheckedTextView c = (CheckedTextView) myListView.getChildAt(i);
if(c.isChecked())
{
String child = c.getText().toString();
selectedChildren.add(child);
}
}
It happens if you do not choose the correct resource for showing your different items. It works fine if you choose the built-in resource android.R.layout.simple_list_item_multiple_choice. The method getCheckedItemPositions is coupled in some way to the built-in resource.
There is no need to handle the checking/unchecking of items within the ListView. It already does it on its own.
What does not seem documented is that the ListView will only do this if:
a ListAdapter is set and
the choice mode is CHOICE_MODE_MULTIPLE and
the ids used by the ListAdapter are stable.
The third point was what drove me crazy for a while.
I am not sure what 'stable' means (I guess that the ids don't ever change while the list is displayed).
As far as the ListView is concerned, it means that the method hasStableIds() in ListAdapter returns true.
I created a simple subclass of ArrayAdapter like this:
public class StableArrayAdapter<T> extends ArrayAdapter<T> {
public StableArrayAdapter(Context context, int textViewResourceId, List<T> objects) {
super(context, textViewResourceId, objects);
}
#Override
public boolean hasStableIds() {
return true;
}
}
(You already have your subclass, so just add the hasStableIds override)
Of course, one needs to add the constructor that one was using with ArrayAdapter.
Once you use this class as your ListAdapter, getCheckedItemPositions() behaves as expected.
One last note: setChoiceMode must be called AFTER setting the list adapter.
This is an old thread but since this basically came up first in current Google search here's a quick way to understand what listView.getCheckedItemPositions() does:
Unless the list Item wasn't 'toggled' at all in your ListView, it wont be added to the SparseBooleanArray that is returned by listView.getCheckedItemPositions()
But then, you really don't want your users to click every list item to "properly" add it to the returned SparseBooleanArray right?
Hence you need to combine the usage of valueAt() AND keyAt() of the SparseBooleanArray for this.
SparseBooleanArray checkedArray = listView.getCheckedItemPositions();
ArrayList<DataEntry> entries = baseAdapter.getBackingArray(); //point this to the array of your custom adapter
if (checkedArray != null)
{
for(int i = 0; i < checkedArray.size(); i++)
{
if(checkedArray.valueAt(i)) //valueAt() gets the boolean
entries.yourMethodAtIndex(checkedArray.keyAt(i)); //keyAt() gets the key
}
}
This adjustment fixed it for me.
Change the getView method so that "int position" is "final int position".
Then do this with your checkbox:
((CheckBox) convertView).setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
list.setItemChecked(position, ((CheckBox) buttonView).isChecked());
}
});
Let me elaborate.
list is a reference to the listview and in my case the adapter is an inner class in the dialog holding the list.
I found this thread by having the same problem but I think I have come up with a workaround that worked for me for unkown reasons. Whenever I tried getting a value I got nothing but if I loop through the list setting all to false it started working just like intended.
This was actually a feature I had implemented where the user could either "Select All" or "Unselect All". I run this method in my onCreate.
private void selectNone() {
ListView lv = getListView();
for (int i = 0; i < lv.getCount(); i++) {
lv.setItemChecked(i, false);
}
}
Now all my values are correct. For getting the values, in my case, just Strings.
private void importSelected() {
ListView lv = getListView();
SparseBooleanArray selectedItems = lv.getCheckedItemPositions();
for (int i = 0; i < selectedItems.size(); i++) {
if (selectedItems.get(i)) {
String item = lv.getAdapter().getItem(selectedItems.keyAt(i)).toString();
}
}
selectNone(); //Reset
}
I hope this helps someone.
I too used the solution gyller suggests that involves "initiating" the listview
ListView lv = getListView();
for (int i = 0; i < lv.getCount(); i++) {
lv.setItemChecked(i, false);
}
before calling getCheckItemPositions(), and it stopped producing erroneous results!
while I do not believe I have tried every variation described here, here is the one that has worked for me :)
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
CheckedTextView retView = (CheckedTextView) convertView;
...
retView.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
CheckedTextView chkVw = (CheckedTextView) v;
// chkVw.toggle();
// chkVw.setChecked(!chkVw.isChecked());
mLstVwWordingSets.setItemChecked(position + 1, !chkVw.isChecked());
}
});
...
}
And later
SparseBooleanArray checkedItemsArray = mLstVwWordingSets.getCheckedItemPositions();
for (int i = 1; i < mLstVwWordingSets.getCount(); i++) //skip the header view
{
if (checkedItemsArray.get(i, false))
Log.d(_TAG, "checked item: " + i);
}
I am accessing position + 1 due to a header view that my list has in place.
HTH
ArrayList<Integer> ar_CheckedList = new ArrayList<Integer>();
for each holer of check box i am using to store it in array
holder.chk_Allow.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
ar_CheckedList.add(position);
}
});
on click of button
for (int i = 0; i < ar_CheckedList.size(); i++)
{
HashMap<String, String> temp=(HashMap<String, String>) contactList.get(ar_CheckedList.get(i));
str_Phone_No=temp.get(TAG_CONTACT_MOBILE);
send(str_Phone_No);
}
Isn't there a rather fundamental difference between 'selected' and 'checked'?
Suspect you want to setItemChecked() from an OnItemSelectedListener...
simply go to the xml where your listview is defined and set property
**android:choiceMode="multipleChoice"**
my xmlfile
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ali.myapplication.MainActivity">
<ListView
android:id="#+id/lvCustomList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:choiceMode="multipleChoice"
/>
</android.support.constraint.ConstraintLayout>
and then in your javafile as:-
SparseBooleanArray checked=lvDetail.getCheckedItemPositions();
for (int i = 0; i < lvDetail.getAdapter().getCount(); i++) {
if (checked.get(i)) {
Toast.makeText(getApplicationContext(),checked.get(i),Toast.LENGTH_SHORT).show();
}
}
ArrayList<String> selectedChildren = new ArrayList<String>();
for(int i = 0;i<list.getChildCount();i++)
{
CheckBox c = (CheckBox) list.getChildAt(i);
if(c.isChecked())
{
String child = c.getText().toString();
selectedChildren.add(child);
}
}
Log.i(TAG, "onClick: " + selectedChildren.size());

Categories

Resources