Android ListView适配器 - 隐藏项目

时间:2015-07-27 15:52:36

标签: java android android-listview

我有一个android listView,它会像这样填充:

final ListView userList = (ListView)root.findViewById(R.id.userList);
UserListAdapter adapter = new UserListAdapter(context, userItemList,
getActivity());
userList.setAdapter(adapter);

UserListAdapter看起来像这样:

if (convertView == null) {
    LayoutInflater mInflater = (LayoutInflater)
            context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    convertView = mInflater.inflate(R.layout.user_item_list, null);
}
final TextView txtButtonFollow = (TextView) convertView.findViewById(R.id.button);
if(user == "showed") {
    button.setVisibility(View.INVISIBLE);
}else {
    button.setVisibility(View.INVISIBLE);
}
return convertView;

由于某种原因,所有用户按钮都会显示(第一个),但是如果我上下滚动列表并且"重新输入"用户项目,按钮被隐藏(这是我需要的)。

有没有人有同样的问题? 是不是可以隐藏元素"滚动"? 我是否必须设置两个user_item_list(一个带按钮,另一个带按钮)?

编辑:这里是完整的getView():

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    UserItem userItem = userItems.get(position);
    RelativeLayout userListItemMain = (RelativeLayout)convertView.findViewById(R.id.userListItemMain);
    String isContact = userItem.getIsContact();

    if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    }

    final TextView txtButton = (TextView) convertView.findViewById(R.id.button);
    if(isContact) {
        txtButton .setVisibility(View.VISIBLE);
    }else{
        txtButton .setVisibility(View.INVISIBLE);
    }
    return convertView;
}

1 个答案:

答案 0 :(得分:3)

你可以改变这个

 UserListAdapter adapter = new UserListAdapter(context, userItemList,getActivity());

UserListAdapter adapter = new UserListAdapter(userItemList,getActivity());

getActivity()会为您提供背景信息。

相应地更改适配器构造函数

使用ViewHolder模式

public static class ViewHolder
{
     TextView txtButton ;
} 

在getView中

  ViewHolder holder;
  if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        holder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.user_item_list, null);
        holder.txtButton  = (TextView) convertView.findViewById(R.id.button); 
        convertView.setTag(holder) 
    } else {

         holder = (ViewHolder) convertView.getTag();
    } 
    UserItem userItem = userItems.get(position);
    String isContact = userItem.getIsContact();

    if(isContact.equals("showed")) {
    holder.txtButton .setVisibility(View.VISIBLE);
   }else{
     holder.txtButton .setVisibility(View.INVISIBLE);
   }

return convertView;

你的if语句

 if(isContact) { // makes no sense. isContact is not boolean