0

我在android中遇到了listview的问题。我有一个带有 3 个文本视图和一个按钮的自定义适配器,其文本根据服务器的响应而变化。实际上,我的应用程序中有搜索朋友的功能,因此列表显示每个用户及其按钮文本上的状态。就像如果已经是朋友,那么按钮文本是朋友并且按钮被禁用。否则添加朋友,并且按钮启用。单击“添加朋友”按钮后,按钮文本更改为“请求已发送”。但问题是,当我单击其他一些按钮的按钮文本时,滚动也会发生变化。请帮我。如果需要,我会放代码。

这是我的适配器类:

class ListViewCustomAdapter extends BaseAdapter {
private static final String REQUEST = "Request";
private static final String ACCEPT = "Accepted";
private static final String RECEIVE = "Receive";
private Activity context;
private ArrayList<FriendList> friendList;
private SessionManager sessionManager;
private String authToken;
private ProgressDialog progressDialog;
ViewHolder mViewHolder;
private HashMap<Integer, String> buttonTextMap;

public ListViewCustomAdapter(Activity activity,
        ArrayList<FriendList> _friendList) {

    this.context = activity;
    this.friendList = _friendList;
    sessionManager = new SessionManager(context);
    authToken = sessionManager.getAuthorizationKey();
    buttonTextMap = new HashMap<Integer, String>();

}

public int getCount() {
    // TODO Auto-generated method stub
    return friendList.size();
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return friendList.get(position);
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

public View getView(final int position, View convertView, ViewGroup parent) {

    LayoutInflater layoutInflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = layoutInflater.inflate(
                R.layout.friend_list_view_item, null);

        mViewHolder = new ViewHolder();
        mViewHolder.profilePicture = (ImageView) convertView
                .findViewById(R.id.friendPicureImageView);

        mViewHolder.friendName = (TextView) convertView
                .findViewById(R.id.firstNameTextView);

        mViewHolder.email = (TextView) convertView
                .findViewById(R.id.emailTextView);

        mViewHolder.gender = (TextView) convertView
                .findViewById(R.id.genderTextView);

        mViewHolder.addButton = (Button) convertView
                .findViewById(R.id.addFriendButton);

        convertView.setTag(mViewHolder);

    } else {
        mViewHolder = (ViewHolder) convertView.getTag();
    }

    byte[] imageByteArray = Base64.decode(friendList.get(position)
            .getFriendProfilePic(), Base64.DEFAULT);

    mViewHolder.profilePicture.setImageBitmap(BitmapFactory
            .decodeByteArray(imageByteArray, 0, imageByteArray.length));

    if (friendList.get(position).getFriendFirstName()
            .equalsIgnoreCase("null")) {
        mViewHolder.friendName.setText(friendList.get(position)
                .getFriendLastName());
    } else if (friendList.get(position).getFriendLastName()
            .equalsIgnoreCase("null")) {
        mViewHolder.friendName.setText(friendList.get(position)
                .getFriendFirstName());
    } else if (friendList.get(position).getFriendLastName()
            .equalsIgnoreCase("null")
            && friendList.get(position).getFriendFirstName()
                    .equalsIgnoreCase("null")) {
        mViewHolder.friendName.setText("No Name");
    } else {
        mViewHolder.friendName.setText(friendList.get(position)
                .getFriendFirstName()
                + " "
                + friendList.get(position).getFriendLastName());
    }

    if (!friendList.get(position).getFriendEmail().equalsIgnoreCase("null")) {
        mViewHolder.email
                .setText(friendList.get(position).getFriendEmail());
    }

    if (!friendList.get(position).getFriendGender()
            .equalsIgnoreCase("null")) {
        if (friendList.get(position).getFriendGender()
                .equalsIgnoreCase(Constants.MALE))
            mViewHolder.gender.setText(Constants.SET_MALE);
        else if (friendList.get(position).getFriendGender()
                .equalsIgnoreCase(Constants.FEMALE)) {
            mViewHolder.gender.setText(Constants.SET_FEMALE);
        }
    }

    if (friendList.get(position).getFriendRequestStatus()
            .equalsIgnoreCase(REQUEST)) {
        /*
         * buttonTextMap.put(position, "Request sent");
         * buttonActiveStateMap.put(position, false);
         */

        mViewHolder.addButton.setText("Request Sent");
        mViewHolder.addButton.setEnabled(false);
    } else if (friendList.get(position).getFriendRequestStatus()
            .equalsIgnoreCase(ACCEPT)) {
        /*
         * buttonTextMap.put(position, "Add friend");
         * buttonActiveStateMap.put(position, true);
         */

        mViewHolder.addButton.setText("Friend");
        mViewHolder.addButton.setEnabled(false);
    } else if (friendList.get(position).getFriendRequestStatus()
            .equalsIgnoreCase(RECEIVE)) {
        /*
         * buttonTextMap.put(position, "Add friend");
         * buttonActiveStateMap.put(position, true);
         */

        mViewHolder.addButton.setText("Accept");
        mViewHolder.addButton.setEnabled(true);
    }

    buttonTextMap.put(position, mViewHolder.addButton.getText().toString());


    Log.d("FriendList", "position in getview===== " + position);
    mViewHolder.addButton.setTag(position);
    mViewHolder.addButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            int which = -1;
               Object obj =  v.getTag();
              if(obj instanceof Integer){
               which  = ((Integer)obj).intValue();
               Log.e("FriendListActivity", "position button 1 ======= "+which);

              }
              if(which >-1){
                  Log.e("FriendListActivity", "position button 2======= "+which);
                }

              Button button = (Button) FriendListActivity.listView.getChildAt(which).findViewById(R.id.addFriendButton); 

            //Button button = (Button) v;
            if (button.getText().toString().equalsIgnoreCase("Accept")) {
                Intent intent = new Intent(context,
                        NotificationsActivity.class);
                context.startActivity(intent);
                context.finish();
            } else {
                int id = button.getId();
                addFriend(button, friendList.get(position)
                        .getFriendUserId(),which);

            }



    }
    });
    return convertView;
}

static class ViewHolder {
    TextView friendName;
    TextView email;
    TextView gender;



    ImageView profilePicture;
    Button addButton;
}

private void addFriend(final Button _button, final String userId,
        final int _position) {
    final JSONObject jsonObject = new JSONObject();

    Log.e("FriendListActivity", "position in addFriend=== " + _position);

    try {
        jsonObject.put("authToken", authToken);
        jsonObject.put("targetFriendId", userId);
        jsonObject.put("requestType", "FriendRequest");
        jsonObject.put("status", "Requested");

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    final Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            progressDialog.dismiss();
            if (msg.what == 1) {

                _button.setText("Request sent");
                _button.setEnabled(false);
                Toast.makeText(context, "Request sent successfully.",
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "Request unsuccessfull.",
                        Toast.LENGTH_LONG).show();
            }

        }
    };

    progressDialog = ProgressDialog.show(context, "", "Loading...");

    new Thread() {
        @Override
        public void run() {

            String response = DoFriendRequest
                    .makeHttpPostRequest(jsonObject);
            Message message = new Message();
            if (response != null) {
                message.what = 1;
                handler.sendEmptyMessage(message.what);
            } else {
                handler.sendEmptyMessage(0);
            }

        }
    }.start();

}
4

1 回答 1

2

所以终于在经过长时间的研究和彻底了解listview对convertview的回收和使用的情况下找到了解决方案。由于我从服务器获取每个按钮的状态,所以在我的 addFriend() 方法中,我只是更新了按下的按钮(仅限视图)的文本,而不是在我从中获取数据的列表中对于列表视图(列表视图的每一行)。所以我做了什么,每当我更新一行按钮的标签状态时,我都必须更新我的数据列表(在我的情况下是通过设置friendList.get(position).setFriendStatus(“null”)来更新我的朋友列表)并调用适配器.notifyDatasetChanged() 之后。我还忘记为按钮的“null”状态添加检查过滤器。如果有人有任何困惑,请问我。

这是我为了解 listview getView() 方法而引用的链接- ListView 的回收机制如何工作

于 2013-05-24T10:14:56.760 回答