I have a ListView that shows the closest word matches to a search.
For example if I search "hi" I get the following results in the ListView
...
hi
hi five
hi-five
high
highlight
....
I am using
ListView.setSelection(wordList.indexOf(searchWord));
ListView.setSelected(true);
The above code puts the selected word "hi" at the top and doesnt highlight the selection.
I want the "hi" to be centrally positioned , selected and highlighted automatically.
See below
...
hello
hello there
hi
hi-five
hi five
...
What code can I use to achieve the above?
Many thanks.
ListView view = (ListView)findViewById(R.id.YourListView);
int height = view.getHeight();
int itemHeight = view.getChildAt(0).getHeight();
view.setSelectionFromTop(position, height/2 - itemHeight/2);
The position (int) is the listitem you want to center in the listview!!
try setSelectionFromTop() you'll have to do the math yourself. setSelection() bring the selected item to the top of the view, which is what you are seeing.
try this.
first, get visible item count of listview
int count=0;
for (int i = 0; i <= listview.getLastVisiblePosition(); i++)
{
if (listview.getChildAt(i)!= null)
{
count++;
}
}
second, scroll the item to the center of listview.
int target = position-count/2;
if (target<0) target = 0;
listview.setSelection(target);
Try this:
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
for more information :
http://developer.android.com/resources/tutorials/views/hello-listview.html
Related
I am trying to get the selected item from grid view in Android development. Here is the list of drawable I used to populate the grid view:
private static Integer[] iconlist = {
R.drawable.food_icon, R.drawable.transport_icon, R.drawable.entertainment_icon,
R.drawable.bill_icon, R.drawable.others_icon, R.drawable.salary_icon,
R.drawable.investment_icon, R.drawable.bonus_icon, R.drawable.medication_icon,
R.drawable.drinks_icon, R.drawable.car_icon, R.drawable.mask_icon,
R.drawable.shopping_icon, R.drawable.lottery_icon, R.drawable.pet_icon,
R.drawable.movie_icon, R.drawable.plant_icon, R.drawable.paint_icon,
};
And gridview on click listener:
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
Toast.makeText(getActivity(), "Grid Item " + (position + 1) + " Selected", Toast.LENGTH_LONG).show();
int selected = position + 1;
for(int i = 0; i < iconlist.length; i++){
if(iconlist[i] == selected){
}
}
}
});
I managed to get the correct integer position based on the clicks. What I am trying to do is based on the selected drawable, I am trying to extract out the string.
For example, when transport icon is clicked, I am trying to get the "transport_icon" string from "R.drawable.transport_icon" and store it as string. However, I not sure how to do it.
Any ideas?
first define a drawable from integer array (the ids)
Drawable drawable = context.getResources().getDrawable(iconlist[n]);
and you can get name of resources like this
String name = context.getResources().getResourceEntryName(ID);
this method should return what you need.
You can try in below way:
Context.getResources().getResourceEntryName(R.drawable.transport_icon)
or
Context.getResources().getResourceName(R.drawable.transport_icon)
Reference: https://developer.android.com/reference/android/content/res/Resources.html#getResourceEntryName(int)
I'm trying to move the item's position on ListView by pressing a button which will move up one row of the list.I tried looking for other answers on SO but their ListView was populated from an ArrayList whilst mine from fileList()
Do I need to somehow sort the files in fileList()? or is using ArrayList enough for me to change their positions?
I used ArrayList to get the item's position
How I populate my ListView
String[] SavedFiles;
String dataDr;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address);
dataDr = getApplicationInfo().dataDir;
showDirFile(dataDr);
}
void showDirFile(String dirpth)
{
String path = dirpth+"/files";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
SavedFiles = new String[file.length];
for (int i=0; i < file.length; i++)
{
Log.d("Files", "FileName:" + file[i].getName());
SavedFiles[i] = file[i].getName();
}
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
SavedFiles);
listView.setAdapter(adapter);
}
How I get the item's position
OnItemClickListener getFileEditContent = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get item's file name according to position
String clickedFile = (String)parent.getItemAtPosition(position);
stringArrayList.add(clickedFile)
// Get item position
intArrayList.add(position);
}
};
you have used String[] SavedFiles; for showing list using adapter.
On click of an Item you want to move it up for that write logic for swapping array items and notify adapter.
Your logic will make the top item to current one and current one to top one.
Hope this will help you.
I managed to solve it myself by using the Collections.swap method
Example
Collections collections;
void positionChange(){
//to store arrays into ArrayList
List<String> newList = new ArrayList<String>(Arrays.asList(myDataFiles));
//to get the item's position # get the first item in array if multiple arrays exist
String currentPos = String.valueOf(intArrayList.get(0));
int oldPos = Integer.valueOf(currentPos);
int newPos = oldPos-1;
//Swap position # move up list
collections.swap(newList, oldPos, newPos);
//store ArrayList data into arrays
myDataFiles = newList.toArray(myDataFiles);
intArrayList.clear();
adapter.notifyDataSetChanged();
}
This will make our selected item move up, but it won't save the state. Meaning the item's position displayed on ListView will go back to the way it was upon closing the app
Okay so I've been able to hightlight an item in a ListView, but it ends up highlighting every fourth item. I'm pretty sure that's because of recycling. Then I had the issue where the highlighted item would go back to normal after I scrolled, and that's also because of recycling. Is there any way to keep it highlighted, or to maybe stop the ListView from recycling?
This is what the code looks like right now...
runTimes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View v, int pos, long id) {
v.setSelected(true);
}
});
This is the code where the highlighted item goes back to normal after you scroll.
to hilight a row you should not touch the view at all. you should use listviews setItemChecked with a selector as the background of your view.
runTimes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View v, int pos, long id) {
runTimes.setItemChecked(pos,true);
}
});
you also need to make sure you keep track of the last position you selected so that you can deselect it when you select a new one
If you want to stop ListView from recycling you should think again if you really need a ListView.
To properly accomplish this with a ListView, though, you need to save the highlighted item states inside of your adapter. Then in getView highlight the items based on their position.
There have been A LOT of questions about saving the state of the ListView items, I'm sure you can find some.
I ended up finding another question that helped me figure out how to do it. This is what I did. In the OnClickListener I check to see if something has been pressed before. If it hasn't been pressed before, then I set the views background color, and prevRunView to the view. If something has been pressed before, then I change the previous view background color to white. After that I do the same thing as before, but for the different view.
if(runIndex == -1){
runIndex = pos;
v.setBackgroundColor(Color.parseColor("#A6A6A8"));
prevRunView = v;
}else{
prevRunView.setBackgroundColor(Color.parseColor("#FFFFFF"));
runIndex = pos;
v.setBackgroundColor(Color.parseColor("#A6A6A8"));
prevRunView = v;
}
In my adapter I wrote this code so it won't seem like it's recycling.
if(ScoreActivity.runIndex == position)
v.setBackgroundColor(Color.parseColor("#A6A6A8"));
else
v.setBackgroundColor(Color.parseColor("#FFFFFF"));
i'm having listview with some items. i placed a Checkbox to display the checkbox with that listitem. I've write onclick method to checkall the checkbox. But, it'll select the item which was in top of the list. What's the problem? Anyone clear me? Thanks in Advance. Sample Code : -
CheckBox c = (CheckBox)findViewById(R.id.checkBox1);
if (c.isChecked())
{
c.setChecked(false);
}
else
{
c.setChecked(true);
}
private OnClickListener checkAllCheckboxes = new OnClickListener(){
public void onClick(View v) {
ListView lv = getListView();
int size = getListAdapter().getCount();
boolean check = lv.isItemChecked(0);
for(int i = 0; i <= size; i++)
lv.setItemChecked(i, !check);
}
}
OR
for(int i=0; i < listView.getChildCount(); i++){
RelativeLayout itemLayout = (RelativeLayout)listView.getChildAt(i);
CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.MyListViewCheckBox);
cb.setChecked(true);
android-unable-to-check-all-the-checkboxes-in-a-custom-listview-because-of-recy
Example2
with that snippet its difficult to point out the issue.
one, the listview reuses the view, maybe that while scrolling the same view is appearing else where.
here is a tutorial http://www.marvinlabs.com/2010/10/custom-listview-ability-check-items/
check it out. or post additional code. particularly, getView in the adapter code.
It happened because at calling of Adapter view it execute at the time of your list view.
So after the you clicked on check box (true) at same number of below screen will be true. for that you have to maintain the Vector.
if(tempVector.get(position)){
holder.box.setChecked(true);
}
else{
holder.box.setChecked(false);
}
try this after your clicking event.
How would one find the position of a specific item within a ListView? (Populated by SimpleCursorAdapter).
The reason I ask: The listview is set to singleChoice mode. When the user closes and reopens the app, I'd like the user's selection to be remembered.
The way I've done it so far is when the user clicks on an item, the ID of the chosen item is saved to preferences. What I need to learn is how to reselect the item in the activity's onCreate method once it's been repopulated.
My code for saving the selected item's ID:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = (Cursor) l.getItemAtPosition(position);
selectedItem = c.getLong(c.getColumnIndex("_id"));
}
(I've tried googling, but only seem to find how to get the position of the selected item)
Thanks!
You should try
//SimpleCursorAdapter adapter;
final int position = adapter.getCursor().getPosition();
API Docs:
public abstract int getPosition ()
Since: API Level 1
Returns the current position of the
cursor in the row set. The value is
zero-based. When the row set is first
returned the cursor will be at positon
-1, which is before the first row. After the last row is returned another
call to next() will leave the cursor
past the last entry, at a position of
count().
Returns
the current cursor position.
Update
To get an item's position based on the id used by the adapter:
private int getItemPositionByAdapterId(final long id)
{
for (int i = 0; i < adapter.getCount(); i++)
{
if (adapter.getItemId(i) == id)
return i;
}
return -1;
}
To get an item's position based on the underlying object's properties (member values)
//here i use `id`, which i assume is a member of a `MyObject` class,
//and this class is used to represent the data of the items inside your list:
private int getItemPositionByObjectId(final long id)
{
for (int i = 0; i < adapter.getCount(); i++)
{
if (((MyObject)adapter.getItem(i)).getId() == id)
return i;
}
return -1;
}
I do this straightforward in my own app:
long lastItem = prefs.getLong(getPreferenceName(), -1);
if (lastItem >= 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
if (lastItem == cursor.getLong(0)) {
spinner.setSelection(cursor.getPosition());
break;
}
cursor.moveToNext();
}
}
Spinner is populated with the cursor's contents, so I just look through them and compare with the selected item id. In your case that would be a ListView.
When you say, "...reselecting the item in the activity's onCreate method...", do you mean that when the user returns to the ListView activity, whatever item was previously chosen, is now currently at the top of the screen (assuming enough items appear in the list below it)?
If so, then from onListItemClick, you should also make an effort to save the value of position, since it tells you the position in the list of the selected item. This would allow you to not need to reverse-lookup the position from the _id.
Or is that for some reason not an option for your purposes? Do you really need to instead figure out the position from the _id?