List View Custom adapter item(button) text repeating on scrolling

我只是一个虾纸丫 提交于 2020-01-03 05:14:43

问题


I am facing problem with listview in android. I've a custom adapter with 3 textviews and a button whose text changes as per response from server. Actually I've a feature of search friend in my app,so the list appears with each user and its status on button text. Like if already friend then button text is Friend and button is disabled.Else Add Friend, and button enabled. After clicking Add Friend text of button changes to Request Sent. But the problem is that when i click on a button text of some other buttons also changes on scrolling. Please help me. If needed I'll put the code.

Here is my adapter class:

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();

}

回答1:


So finally I found the solution after a long research and completely understanding listview's recycling and use of convertview. As I am getting the status for each button from server, so in my addFriend() method I was just updating the text of the button(of the view only) which is pressed, but not in the list from where I am getting the data for the listview(each row of listview). So what I did, whenever I update the label-status of the button for a row, I've to update my datalist(in my case friendList by setting friendList.get(position).setFriendStatus("null")) and call adapter.notifyDatasetChanged() after that. I also forgot to add a check-filter for the "null" status of button. If anyone has any confusion please ask me.

This is the link which I referred for understanding listview getView() method- How ListView's recycling mechanism works



来源:https://stackoverflow.com/questions/16709785/list-view-custom-adapter-itembutton-text-repeating-on-scrolling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!