Deselect current list view item if selected again - java

I currently have a list view in which you can select an item and it will highlight the currently selected item. But I would like to set it sot that so that if the user clicks on the same item currently selected in the list again it will unhighlight the list item and have no list item currently selected/
currentUsersCameras.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> parent, View view, final int position, long id) {
for (int i = 0; i < parent.getChildCount(); i++) {
parent.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
view.setBackgroundColor(Color.rgb(3, 169, 244));
}
}
});

Listview/Recyclerview items requires you to handle if and else cases always. So if you want to do something for one item and not for another item, and similarly if you want to do and undo the same thing to the same item, handle both IF and ELSE

Related

Spinner Item re-selected

I am implementing a spinner with auto fill text view and adding same list in adapter of Spinner and auto fill text view,
If I select a item from spinner it will be set in autoFillTextView,
But the problem is if I select a item from spinner and then make a change in autofillTextView, and then again select same item from spinner then controller is not going back to spinner onSelected method,
Thanks in advance.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
case R.id.spinnerGroupName:
actvMatchGroup.setText("");
//Your Another Action Here.
for (int i = 0; i < groupList.size(); i++) {
if (groupName[position] == groupList.get(i).getGroupName()) {
groupId = Integer.parseInt(groupList.get(i).getGroupId());
group_id = groupId;
}
}
tvMatchGroup.setText(groupName[position]);
actvMatchGroup.setText(groupName[position]);
break;
}

Dependent dropdown using Exposed Drop-Down Menu and AutoCompleteTextView

#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Define city spinner but we will populate the option through the selected state
policeStationSelectDropdown = findViewById(R.id.psAutoCompleteText);
// Obtain the selected district
selectedDistrict = districtSelectDropdown.getSelectedItem().toString();
Toast.makeText(Complaint_page.this,selectedDistrict, Toast.LENGTH_SHORT).show();
// int parentId = parent.getId();
if (parent.getId() == R.id.districtAutoCompleteText)
getSelectedItem() is showing error??
How to use this with autoCompleteTextView. I want dependent dropdown using Exposed Drop-Down Menu and autoCompleteTextView using JAVA.

Why is the wrong ListView item highlighted?

I implemented a ListView, and the method OnItemLongClick to highlight the selected item, but when I select an item, if I scroll the ListView, I find that another item is highlighted.
I'm using this code:
list.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
arg1.setBackgroundColor(Color.BLUE);
return true;
}
});
you can use android:listSelector property instead of onItemLongClick

What is the equivalent listview.setSelection in case of Recycler View

In the case of a ListView if we want to make a particular item selected we use the setSelection method. How do we do this in case of RecyclerView?
Use RecyclerView LayoutManager to scroll item at position
recyclerView.getLayoutManager().scrollToPosition(position)
Check
scrollToPositionWithOffset(int position, int offset)
scrollToPositionWithOffset(5,0);
from LinearLayoutManager
Scroll to the specified adapter position with the given offset from resolved layout start.
pass offset as 0 if you want selection at top
This worked for me
Check
recyclerView.scrollToPosition(cursor.getcount() - 1);
ListView.setSelected() does (at least) two things:
It sets the item in the list to be selected (while removing the selection from another item - if such exists)
It scrolls the list so that the item will be visible on the screen.
To achieve 2. either call scrollToPosition() method of RecyclerView (as indicated by Loser), or call one of the scrolling methods of the LayoutManager object depending on your desired scrolling behavior.
For example,
recyclerView.getLayoutManager().smoothScrollToPosition()
You may want to scroll the minimum so that the selected item shows on the screen.
If so and you are using LinearLayoutManager or GridLayoutManager, you can build such scroll logic based on
findFirstCompletelyVisibleItemPosition() and findLastCompletelyVisibleItemPosition() defined in these classes.
Achieving 1. is more tricky. You may want to use the following recipe:
First define a background color in colors.xml, item_state_selected_color, to be used when an item is selected.
In your onCreateViewHolder() implementation create a StateListDrawalbe and set it as the background of the view.
Say something like this:
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
// inflate the item view
View itemView = LayoutInflater.from(viewGroup.getContext()).
inflate(itemResourceId,viewGroup, false);
// create color drawable by a resorce id
ColorDrawable colorDrawableSelected =
new ColorDrawable(resources.getColor(R.color.item_state_selected_color));
// create StateListDrawable object and define its states
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{android.R.attr.state_selected}, colorDrawableSelected);
stateListDrawable.addState(StateSet.WILD_CARD, null);
// set the StateListDrawable as background of the item view
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
itemView.setBackgroundDrawable(stateListDrawable);
}
else {
itemView.itemView.setBackground(stateListDrawable);
}
// create view holder object providing it with the item view
return new YourViewHolder(itemView);
}
In YourAdapter object (or elsewhere) save a variable, mCurrentSelectedPosition (probably initialized to -1) that holds the current selected position.
Still in the adapter, define handler for clicks on recycler view items, depending on your click logic. For example:
void onItemClick(int position) {
YourViewHolder yourViewHolder;
int oldSelectedPosition = mCurrentSelectedPosition;
if (position != mCurrentSelectedPosition) {
mCurrentSelectedPosition = position;
if (oldSelectedPosition != -1) {
yourViewHolder = findViewHolderForPosition(oldSelectedPosition);
yourViewHolder.itemView.setSelected(false);
}
yourViewHolder = findViewHolderForPosition(mCurrentSelectedPosition);
yourViewHolder.itemView.setSelected(true);
}
}
Next, in the constructor of YourViewHolder set listener to clicks on the item:
public YourViewHolder(View itemView,YourAdapter adapter) {
mAdapter = adapter;
// ... other code here ...
itemView.setOnClickListener(this);
}
Still in YourViewHolder override the onClick() method to delegate handling to the adapter. like this
#Override
public void onClick(View v) {
mAdapter.onItemClick(getPosition());
}
Now there is just last problem to solve - we need to keep track of the selected item with respect to recycling.
#Override
public void onBindViewHolder(YourViewHolder yourViewHolder, int position) {
if (position == mCurrentSelectedPosition) {
yourViewHolder.itemView.setSelected(true);
}
else {
yourViewHolder.itemView.setSelected(false);
}
// ... other code here ...
}
Good luck!

Adding custom data to ListView & ArrayAdapter items

I'm creating an Android application. Inside a Fragment I have a ListView that is populated using an ArrayAdapter and an ArrayList. I'm using android.R.layout.simple_list_item_1 for the layout for the list items. I want to have an OnItemClickListener, so that when an item is clicked it will show another Activity based on its data.
The problem is, there may be items with the same name. I'd like to attach an ID value to each of the elements, so that my code can distinguish them from each other.
My items that I use to populate the list are of a custom class to hold their data, but the important fields here are the ID and the name (which is shown in the ListView).
My code for populating the ListView:
List<String> items;
ArrayAdapter<String> adapter;
List<MyCustomDataObject> listOfDataObjects;
...
// Get the ListView
ListView list = (ListView) layoutRootView.findViewById(R.id.listView1);
// Create the item List and the ArrayAdapter for it
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
// Set the list adapter
list.setAdapter(adapter);
// Add the data items
for (MyCustomDataObject obj : listOfDataObjects) {
items.add(obj.name);
}
items.add(getResources().getString(R.string.no_items));
// Create the item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Open the Activity based on the item
}
});
How could I add an ID to the list items for identifying each item?
The solution is quite simple actually.
You're populating the ListView from a List. The List is an ordered collection of items, so when adding it as the datasource for the ListView you will always know the index of each item.
So when selecting an item from the ListView you get the position of the View clicked. This position will correspond to the position in your List.
You won't really need the id field of your MyCustomDataObject, but of course when you populate the List of MyCustomDataObject you could use a normal for-loop (not enhanced) and use the index to set the id of each MyCustomDataObject.
Lookup the position in listOfDataObjects to find the ID:
// Create the item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position==listOfDataObjects.size()) { .... no_items clicked ... }
else {
MyCustomDataObject obj = listOfDataObjects.get(position);
... // Open the Activity based on the item
}
}
});

Categories