我有一个ListActivity
实现onListItemClick()
并调用doSomething()
该类的函数.后者包含l.setSelection(position)
其中l
是ListView
对象.
现在有onClickListener()
一个按钮点击,它会执行一些操作并且也会调用doSomething()
.
在第一种情况下,所选项目适当定位,但在后者中,没有任何反应.
有关这种奇怪行为的任何线索以及我如何使其发挥作用?
mei*_*ilp 104
也许你需要使用功能:
ListView.setItemChecked(int position, boolean checked);
Run Code Online (Sandbox Code Playgroud)
小智 65
requestFocusFromTouch()
在调用setSelection()
方法之前使用
mr_*_*yde 33
我知道这是一个老问题,但我遇到了类似的问题,我以这种方式解决了这个问题:
mListView.clearFocus();
mListView.post(new Runnable() {
@Override
public void run() {
mListView.setSelection(index);
}
});
Run Code Online (Sandbox Code Playgroud)
Com*_*are 13
setSelection()
不一定有视觉冲击力.仅当您使用D-pad /轨迹球导航列表时,才会显示选择栏.如果您点击屏幕上点击某些内容,选择栏会短暂显示并消失.
因此,setSelection()
如果活动未处于触摸模式(即,用户做的最后一件事是使用D-pad /轨迹球),则仅具有视觉影响.
鉴于您提供的描述,我不是100%肯定这会解释您的现象,但我认为值得一试......
如果您为ListView使用适配器,请将此代码添加到适配器:
public class MyAdapter extends
ArrayAdapter<MyClass> {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflator.inflate(R.layout.my_adapter, null);
} else {
rowView = (View) convertView;
}
//...
// set selected item
LinearLayout ActiveItem = (LinearLayout) rowView;
if (position == selectedItem)
{
ActiveItem
.setBackgroundResource(R.drawable.background_dark_blue);
// for focus on it
int top = (ActiveItem == null) ? 0 : ActiveItem.getTop();
((ListView) parent).setSelectionFromTop(position, top);
}
else
{
ActiveItem
.setBackgroundResource(R.drawable.border02);
}
}
private int selectedItem;
public void setSelectedItem(int position) {
selectedItem = position;
}
}
Run Code Online (Sandbox Code Playgroud)
在您的活动中:
myAdapter.setSelectedItem(1);
Run Code Online (Sandbox Code Playgroud)