Android ListView setSelection() does not seem to work

前端 未结 17 1685
情歌与酒
情歌与酒 2020-11-28 06:45

I have a ListActivity that implements onListItemClick() and calls a doSomething() function of the class. The latter contains l.s

17条回答
  •  离开以前
    2020-11-28 06:58

    If you use an Adapter for your ListView add this code to your adapter:

    public class MyAdapter extends
            ArrayAdapter {
    
    
        @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;
        }
    
    }
    

    In your Activity:

    myAdapter.setSelectedItem(1);
    

提交回复
热议问题