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
精彩评论