解决 listview 人工设置选择值 setSelection(position) 无效

貌似 人工设置 Listview中某一项为 选中, 使用


  setSelection(position)无效。


查了一下, 需要在 适配器里解决


package zms.zte2014.mydrawlayout1.myadapter;

import java.util.List;

import zms.zte2014.mydrawlayout1.R;
import zms.zte2014.mydrawlayout1.bean.MenuInfo;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


public class Myadapter5 extends BaseAdapter {

 private List userlist;
 private Context context;
 private LayoutInflater inflater;

  //当前所在行, 如果nowpos不设初始值的话 ,默认第0个会选中
 private static int nowpos=10000;

 public final class ListItemView { // 自定义控件集合

  public TextView menuname;
  public ImageView  menuimg;
  public LinearLayout menulay;

 }

 public Myadapter5(Context context, List users) {
  super();
  this.context = context;

  userlist = users;
 }

 @Override
 public int getCount() {

  return userlist.size();
 }

 @Override
 public Object getItem(int position) {
  // TODO Auto-generated method stub
  return userlist.get(position);

 }

 @Override
 public long getItemId(int position) {
  return position;
 }

    public void setSelected(int setpos) {
     nowpos = setpos;
        notifyDataSetChanged();
}
   
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

 
  // 自定义视图
  ListItemView listItemView = null;

  if (convertView == null) {
   listItemView = new ListItemView();
   // 获取list_item布局文件的视图
   inflater = LayoutInflater.from(parent.getContext());
   convertView = inflater.inflate(R.layout.list_items, null);
   // 获取控件对象
   // listItemView.image =
   // (ImageView)convertView.findViewById(R.id.imageItem);
   listItemView.menuimg = (ImageView) convertView
     .findViewById(R.id.menu_img);
   listItemView.menuname = (TextView) convertView
     .findViewById(R.id.menu_name);
   MenuInfo MenuInfo = userlist.get(position);
   listItemView.menuname.setText(MenuInfo.getName());
   listItemView.menuimg.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_drawer));
   
   convertView.setTag(listItemView);
  } else {
   listItemView = (ListItemView) convertView.getTag();
  }
      
    
     listItemView.menulay=(LinearLayout)convertView.findViewById(R.id.menu_lay);
      
        listItemView.menulay.setBackgroundResource(R.drawable.actionbar_item_pressed);
       
      if(position==nowpos)
      {
         listItemView.menulay.setBackgroundResource(R.drawable.actionbar_item_normal);
      }
 
  return convertView;
 }

}


在 listvew itemonclick里


  menuListView.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView parent, View view,
     int position, long id) {

    

    listViewAdapter.setSelected(nowItem);

   }
  });

你可能感兴趣的:(安卓开发)