i have a spinner which i catch onClick like that:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
position = pos;
}
public void onNothingSelected(AdapterView<?> arg0) {
}
I want to check if String for example String example = "example" is in the Spinner ItemList and get its position, Is it possible?
with
spinner.getSelectedItem().toString();
you can get the Text which is currently selected.
with
spinner.getSelectedItemPosition();
you can get the current position.
You can compare the selected String like this:
if(spinner.getSelectedItem().toString().equals("example")){
//do something
};
for (int i = 0; i < adapter.getCount(); i++) {
if (mSpinner.getItemAtPosition(i).equals(MY_STRING)) {
mSpinner.setSelection(i);
break;
}
}
if you wish to set an item on spinner init onNothingSelected won't help you here since this callback is called only when selected item is removed from the list of available items.
Callback method to be invoked when the selection disappears from this
view. The selection can disappear for instance when touch is activated
or when the adapter becomes empty.
docs
Related
I am working on the custom Listview using BaseAdapter. I am facing one small issue after tap on listview item that particular row gets highlighted but after that if i'll tap one another list item it's highlighted but still the older one it remains same it's not going to it's previous state.
I want to see one item should select at one time.
MainActivity.java
if (musicRealmResults.get(currentIndex).isSelected() == false) {
musicRealmResults.get(currentIndex).setIsSelected(true);
playSong(currentIndex, true);
adapter.notifyDataSetChanged();
} else {
musicRealmResults.get(currentIndex).setIsSelected(false);
adapter.notifyDataSetChanged();
}
MusicAdapter.java
if (musicRealmResults.get(position).isSelected()) {
Typeface tf = Typeface.createFromAsset(mContext.getAssets(), "fonts/fonts_bold.otf");
holder1.albumsTextView.setTypeface(tf);
holder1.equalizerView.setVisibility(View.VISIBLE);
holder1.albumsImageView.setVisibility(View.INVISIBLE);
holder1.equalizerView.animateBars();
} else {
Typeface tf = Typeface.createFromAsset(mContext.getAssets(), "fonts/fonts_regular.otf");
holder1.albumsTextView.setTypeface(tf);
holder1.equalizerView.setVisibility(View.GONE);
holder1.albumsImageView.setVisibility(View.VISIBLE);
holder1.equalizerView.stopBars();
}
Please kindly go through my post and suggest me how to do select and deselect in a listview row.
Loop through all your array elements and set check state to false, then set currentIndex to true.
MainActivity
for(int i =0 ; i < musicRealmResults.size() ; ++i){
musicRealmResults.get(i).setIsSelected(false);
}
musicRealmResults.get(currentIndex).setIsSelected(true);
playSong(currentIndex, true);
adapter.notifyDataSetChanged();
Seems that you weren't able to setSelected(false) your previous item.
Please check setChoiceMode() of ListView or you may just reset your previous item to setSelected(false).
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
musicRealmResults.get(currentSelected).setIsSelected(false); //Reset previous
currentSelected = position; //Save currentPosition to for reset later
.....todos
}
This is a good alternative too, if u dont want to loop through the rest of positions to deselect them.
int prevSelection =-1; //nothing selected
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (prevSelection==-1) //nothing selected
{
musicRealmResults.get(position).setIsSelected(true);
adapter.notifyDataSetChanged();
prevSelection = position;
}else if (prevSelection == position) //deselect previously selected
{
musicRealmResults.get(position).setIsSelected(false);
adapter.notifyDataSetChanged();
prevSelection = -1;
}else // Some other selection
{
musicRealmResults.get(prevSelection).setIsSelected(false);
musicRealmResults.get(position).setIsSelected(true);
adapter.notifyDataSetChanged();
prevSelection = position;
}
You can manage this in your model class. Just make a toggle Boolean isSelected with its getter and setter, When user tap on list item check whether its already selected or not, if not then mark it as selected and update the Boolean value in your model class.
mListLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(list.get(position).getisSelected()){
// list item is already selected.
mListLayout.setBackgroundColor(Color.WHITE); // normal color
list.get(position).setisSelected(false);
}
else{
// list item is not selected, make it selected
mListLayout.setBackgroundColor(Color.GRAY); // selected color
list.get(position).setisSelected(true);
}
notifyDataSetChanged();
}
});
Try Below Code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if (musicRealmResults.get(position).isSelected() == false)
{
musicRealmResults.get(position).setIsSelected(true);
playSong(position, true);
adapter.notifyDataSetChanged();
}
else
{
musicRealmResults.get(position).setIsSelected(false);
adapter.notifyDataSetChanged();
}
}
});
I have a list view where I am filtering items through a SearchView. On activating the state for an item, it is not getting the correct item instead getting it from the position. To make it more clear, please refer to the below screenshots:
Search for keyword com and selected the filtered item (i.e activated_state)
On clearing the filter, when the position of the items changes it does not keep track of the selected item i.e com.android.gesture.builder:
I want the selection to be correct regardless of the position change.
My code in MainActivity for this section:
apps.setChoiceMode(apps.CHOICE_MODE_MULTIPLE_MODAL);
apps.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (apps.isItemChecked(position)) {
Adapter.getItem(position);
Toast.makeText(getApplicationContext(), "CHECKED", Toast.LENGTH_LONG).show();
count = count + 1;
mode.setTitle(count + "items selected");
list_apps.add(Adapter.filteredData.get(position).packageName);
list_apps.trimToSize();
}
else {
Toast.makeText(getApplicationContext(), "UNCHECKED" , Toast.LENGTH_LONG).show();
count--;
mode.setTitle(count + "items selected");
list_apps.remove(Adapter.filteredData.get(position).packageName);
list_apps.trimToSize();
}
I am using an extended baseAdapter, please let me know if you need to see that code as well.
Update:
I am having OnItemClick listener in the code:
apps.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
/*
for (int i = 0; i < packageList.size(); i++) {
TextView txtview = ((TextView) arg1.findViewById(R.id.textView1));
product = txtview.getText().toString();
list_apps.add(Adapter.filteredData.get(arg2).packageName);
//Toast.makeText(MainActivity.this, product,
// Toast.LENGTH_SHORT).show();
//for
}
*/
String selection;
selection = Adapter.filteredData.get(arg2).packageName;
string = (String) Adapter.getItem(arg2);
//list_apps.trimToSize();
Toast.makeText(MainActivity.this, selection,
Toast.LENGTH_SHORT).show();
I am using activated_state for the item selected on filtering and maintaining that selection.
If i am not getting wrong, then you need to use OnItemClick lisenter, and get item like this.
Search View Change position of list item, but when we fetch our item from adapter, it return currect item.
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
SString itemName = (String) adapter.getAdapter().getItem(position);
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
You can make a function getVisibleArray() in your adapter, and call it from your onItemClickListener.
in setOnClickListener:
People personInFocus = (People) adapter.getVisibleArray().get(position);
And in adapter:
public ArrayList<People> getVisibleArray() {
return mDisplayedValues;
}
Which is your filtered array.
Ive tested it and it works.
I am working on my first ever android app, and I'm creating basic exercise/calorie counter. I have two spinners, one for the selected type of exercise, and one for the time spent preforming said exercise in minutes. I need to be able to check the value/position of both spinners so I can do something like this:
PSUEDO CODE:
if(Exercise spinner = "push-ups")
{
CaloriesBurned = TimeSpinnerValue*450
}
if(Exercise spinner = "sit-up")
{
CaloriesBurned = TimeSpinnerValue*350
}
etc . . . nothing fancy. My spinners are populated from a String Array in my String.xml. But I dont know how get the value of the spinner so I can use it in some IF statements in my java code.
use like this for compair any string with your spinner.
spinner.equals("push-ups");
You need to implement OnItemSelectedListener for getting the selected value from the Spinner. Then override,
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
int id = parent.getId();
switch (id) {
case R.id.first_spinner:
// your stuff here
break;
case R.id.second_spinner:
// your stuff here
break;
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
String selectedString = (String) (yourSpinner.getAdapter()).getItem(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}});
check this link fro more info
Generically, you'll want to follow this pattern:
SpinnerAdapter adapter = Spinner.getAdapter();
int position = Spinner.getSelectedItemPosition();
Object value = adapter.getItem(position);
Since you are loading it with String values, you can then cast value to a String.
Have some field in your activity to hold value of spinner, initialize with some defaultvalue
implement onItemSelectedListener on spinners, and in onItemSelected get value of selected item, by position argument of onItemSelected(AdapterView adapterView, View view, int position, long id)
I have list view with names and numbers and checkbox populated from contacts with SimpleAdapter, and on item click I listen event and change color of item, also I want to change checkbox to enabled and after user click one more time on the same item I want to deselect that item.
How can I do that?
Thanks Wolf.
This is my code, I can successfully change color, but I don't now how to change checkbox state for that specific item and than on second click to change that state again:
lImenik.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
// TODO Auto-generated method stub
Object obj = lImenik.getItemAtPosition(position);
String tmp = obj.toString();
view.setBackgroundColor(Color.GRAY);
for(int i = 0; i < adapter.getChildCount(); i++){
if(i == position){
if(position != prePos){
adapter.getChildAt(i).setBackgroundColor(Color.GRAY);
prePos = position;
} else {
adapter.getChildAt(i).setBackgroundColor(0x191919);
prePos = -1;
}
}
}
}
});
}
The method
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id)
provides you the view of row which you have clicked. All what you have to do is to mark or unmark the checkbox in that view. You can do that by
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
// TODO Auto-generated method stub
Object obj = lImenik.getItemAtPosition(position);
CheckBox checkbox = ( CheckBox ) view.findViewById ( R.id.your_checkedbox_id );
checkbox.setChecked ( !checkbox.isChecked() ) ;
But you should have array , or a boolean value for your objects so that at the end you can know that Which object are marked are check and which are not
hello frnds i want to change background color (white on selection) of list on selection of list in listview and if i select any other position then first selected row comes to its previous state and currently selected rows background become white.so how to do this
public void onListItemClick(ListView parent, View v, int position, long id) {
super.onListItemClick(parent, v, position, id);
//do some stuff here
Toast.makeText(getApplicationContext(), "You have selected"+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
I wouldn't do that in code, since you later on might want to change colors, and you shouldn't have "layout/styling" code hardcoded.
Do instead create a style, and apply that to the ListView in your xml. You can read about how you do that in this thread:
ListSelector applies to the entire list
Your list view click listener:
yourlistView.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
yourAdapter.toggleSelected(position);
yourAdapter.notifyDataSetChanged();
}
});
Then make an ArrayList in your adapter and initialize it to store all the positions of your list view items:
public ArrayList<Integer> selectedIds = new ArrayList<Integer>();
int length = yourmainarraylist.size();
for(int i = 0; i < length; i++){
selectedIds.add(0);
}
then put a check in getView to toggle the background:
if (selectedIds.get(position)==1)
convertView.setBackgroundResource(R.drawable.list_row_selected);
else
convertView.setBackgroundResource(R.drawable.list_row);
and put this method in your adapter
public void toggleSelected(int position) {
selectedIds.set(position, (selectedIds.get(position) == 0));
}