check if certain position is showing in ListView - java

I want to know if a certain position in a list view is currently shown. Let us say I have a list of 20 Items, how do i check if postion 9 i among the shown items as there may be multiple items on the screen.
In my App, i automatically scroll a List view for the user so i need to know if this postion is already somewhere on the screen

You can use the below code snippet for checking a specific list position is currently visible in list view.
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//Specify the list index that you want to check visibility
int listItemIndex = 9;
View listItem = getListView().getChildAt(listItemIndex);
if (listItem != null && listItem .getVisibility() == View.VISIBLE) {
//The list item is visible
}
}
Get all list items visible on the scroll
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//Loop to get tids of all completely visible List View's item scrolled on screen
for (int listItemIndex = 0; listItemIndex<=getListView().getLastVisiblePosition()- getListView().getFirstVisiblePosition(); listItemIndex++) {
//Specify the list index that you want to check visibility
View listItem = getListView().getChildAt(listItemIndex);
if (listItem != null && listItem .getVisibility() == View.VISIBLE) {
//The list item is visible
}
}
}

Related

Android grid view on click listener get selected item

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)

How would you set the value of a textview based on a value of a spinner?

I am trying to set the value of a textview based on what is selected in the spinner. For example if the cubs were the first element in the list and selected it would set the textview to their hometown. This is what I have so far but it seems to not update the textview.
public void onItemSelected (AdapterView < ? > parent, View view,int position, long id){
TextView mTextView = (TextView) findViewById(R.id.textView);
if(R.id.spinner == 0){
mTextView.setText("Chicago");
}
This condition doesn't seem to make sense:
if(R.id.spinner == 0){
mTextView.setText("Chicago");
}
I think what you want to do is check the int position parameter instead:
if(position == 0){
mTextView.setText("Chicago");
}

List View Android App

I need android list view project with following details:
should contain 10 rows and should show only 3 rows at a time,
should have up and down arrows to it which moves rows up or down to view ,
if it is top of list up arrow should disabled and its bottom of list down arrow should disabled.
Any one please help me and make this code thanks in advance
For a ListView with 3 rows you'll need to have a custom adapter and override it's getView() method. You can inflate a layout with 2 buttons here and add OnClickListener to both of them. Your OnClickListener must override onClick() method whose body must be something like below:
public void onClick(View v) {
int id = v.getId();
int currentIndex = listView.indexOfChild(v.getParent());
View view = listView.getChildAt(currentIndex);
switch(id) {
case upButtonId:
listView.removeView(view);
listView.addView(view, currentIndex--);
if(currentIndex == 0)
//disable Up Button
break;
case downButtonId:
listView.removeView(view);
listView.addView(view, currentIndex++);
if(currentIndex == listView.getChildCount() - 1)
//disable Down Button
break;
}
}

Get position of an item within a ListView?

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?

Android ListView center selection

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

Categories

Resources