android-PopupWindow内的ListView问题
作者:互联网
我在PopupWindow中有一个ListView. PopupWindow像这样初始化
window.setContentView(root);
window.setTouchable(true);
window.setFocusable(true);
window.setOutsideTouchable(true);
window.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
window.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
然后是ListView:
fileList = (ListView) root.findViewById(R.id.explorer_list);
fileList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
fileList.setSelector(android.R.drawable.screen_background_light_transparent);
fileList.setOnItemClickListener(this);
[...]
@Override
public void onItemClick(AdapterView<?> adapter, View v, int pos, long id) {
selected = (File) fileList.getItemAtPosition(pos);
}
像这样,一切正常,除了在滚动ListView之前选择器不会显示在选择器上为止(尽管正确选择了该项目,但在列表滚动之前,视觉上没有显示所选内容).
如果我将PopupWindow设置为不可聚焦,则视觉选择可以正常工作(单击该项目时可以在视觉上选择该项目),但是从不调用onItemClick(),因此无法获得所选项目.
在两种情况下,即使存在选定的项目,ListView.getSelectedItem()始终返回null.
关于如何解决这种情况有什么想法?提前致谢.
解决方法:
我最终使用了一个自定义适配器来存储选定的值,并从那里使用它进行标记:
public class FileExplorerAdapter extends ArrayAdapter<File> {
/** File names */
private List<File> values = new ArrayList<File>();
/** Currently selected position */
private int selected = -1;
public FileExplorerAdapter(Context context, List<File> values) {
super(context, R.layout.explorer_row, values);
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// I know that my layout is always a TextView
TextView row = (TextView) convertView;
if (row == null) {
row = (TextView) ViewHelper.inflateViewById(getContext(),
R.layout.explorer_row);
}
// More code...
// Set up the background for selected element
if (selected == position) {
row.setBackgroundColor(Color.LTGRAY);
// Override background selector
} else {
row.setBackgroundColor(Color.TRANSPARENT);
}
// More code...
return row;
}
/** This sets the selected position */
public void setSelected(int position) {
selected = position;
}
}
在为关联的ListView实现OnItemClickListener的类上,我在适配器中设置了当前选定的项目.
@Override
public void onItemClick(AdapterView<?> adapter, View v, int pos, long id) {
FileExplorerAdapter fileadapter = (FileExplorerAdapter) fileList
.getAdapter();
fileadapter.setSelected(pos);
}
标签:popupwindow,listview,android 来源: https://codeday.me/bug/20191031/1978641.html