列表视图定义适配器项目(按钮)的文本重复上滚动 [英] List View Custom adapter item(button) text repeating on scrolling

查看:126
本文介绍了列表视图定义适配器项目(按钮)的文本重复上滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在面临的问题与Android的列表视图。我曾与3 textviews自定义适配器和一个按钮,其文本更改为每从服务器响应。其实我在我的应用程序搜索朋友的功能,这样的列表将显示与每个用户及其对按钮文本状态。就像如果已经好友,则按钮上的文字是朋友和按钮disabled.Else添加好友,并启用按钮。点击添加按钮变化朋友文本后请求发送的。但问题是,当我的一些其他按钮一个按钮,点击文字也改变上滚动。请帮帮我。如果需要的话,我会放$ ​​C $ C。

下面是我的适配器类:

 类ListViewCustomAdapter延伸BaseAdapter {
私有静态最后弦乐REQUEST =请求;
私有静态最后弦乐ACCEPT ​​=接受;
私有静态最后弦乐接收=接收;
私人活动范围内;
私人的ArrayList<&好友列表GT;好友列表;
私人是SessionManager是SessionManager;
私人字符串的authToken;
私人ProgressDialog progressDialog;
ViewHolder mViewHolder;
私人的HashMap<整数,字符串> buttonTextMap;公共ListViewCustomAdapter(活动活动,
        ArrayList的<&好友列表GT; _好友列表) {    this.context =活动;
    this.friendList = _friendList;
    是SessionManager =新是SessionManager(背景);
    的authToken = sessionManager.getAuthorizationKey();
    buttonTextMap =新的HashMap<整数,字符串>();}公众诠释的getCount(){
    // TODO自动生成方法存根
    返回friendList.size();
}公共对象的getItem(INT位置){
    // TODO自动生成方法存根
    返回friendList.get(位置);
}众长getItemId(INT位置){
    // TODO自动生成方法存根
    返回的位置;
}公共查看getView(最终诠释的立场,观点convertView,父母的ViewGroup){    LayoutInflater layoutInflater =(LayoutInflater)上下文
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    如果(convertView == NULL){
        convertView = layoutInflater.inflate(
                R.layout.friend_list_view_item,NULL);        mViewHolder =新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 =(按钮)convertView
                .findViewById(R.id.addFriendButton);        convertView.setTag(mViewHolder);    }其他{
        mViewHolder =(ViewHolder)convertView.getTag();
    }    字节[] = imageByteArray Base64.de code(friendList.get(位置)
            .getFriendProfilePic(),Base64.DEFAULT);    mViewHolder.profilePicture.setImageBitmap(BitmapFactory
            由Matchi.com提供回到codeByteArray的(imageByteArray,0,imageByteArray.length));    如果(friendList.get(位置).getFriendFirstName()
            .equalsIgnoreCase(空)){
        mViewHolder.friendName.setText(friendList.get(位置)
                .getFriendLastName());
    }否则如果(friendList.get(位置).getFriendLastName()
            .equalsIgnoreCase(空)){
        mViewHolder.friendName.setText(friendList.get(位置)
                .getFriendFirstName());
    }否则如果(friendList.get(位置).getFriendLastName()
            .equalsIgnoreCase(空)
            &功放;&安培; friendList.get(位置).getFriendFirstName()
                    .equalsIgnoreCase(空)){
        mViewHolder.friendName.setText(NO NAME);
    }其他{
        mViewHolder.friendName.setText(friendList.get(位置)
                .getFriendFirstName()
                +
                + friendList.get(位置).getFriendLastName());
    }    如果(!friendList.get(位置).getFriendEmail()。equalsIgnoreCase(空)){
        mViewHolder.email
                .setText(friendList.get(位置).getFriendEmail());
    }    如果(!friendList.get(位置).getFriendGender()
            .equalsIgnoreCase(空)){
        如果(friendList.get(位置).getFriendGender()
                .equalsIgnoreCase(Constants.MALE))
            mViewHolder.gender.setText(Constants.SET_MALE);
        否则,如果(friendList.get(位置).getFriendGender()
                .equalsIgnoreCase(Constants.FEMALE)){
            mViewHolder.gender.setText(Constants.SET_FEMALE);
        }
    }    如果(friendList.get(位置).getFriendRequestStatus()
            .equalsIgnoreCase(REQUEST)){
        / *
         * buttonTextMap.put(位置,请求派);
         * buttonActiveStateMap.put(位置,FALSE);
         * /        mViewHolder.addButton.setText(请求发送);
        mViewHolder.addButton.setEnabled(假);
    }否则如果(friendList.get(位置).getFriendRequestStatus()
            .equalsIgnoreCase(接受)){
        / *
         * buttonTextMap.put(位置,加为好友);
         * buttonActiveStateMap.put(位置,真正的);
         * /        mViewHolder.addButton.setText(朋友);
        mViewHolder.addButton.setEnabled(假);
    }否则如果(friendList.get(位置).getFriendRequestStatus()
            .equalsIgnoreCase(接收)){
        / *
         * buttonTextMap.put(位置,加为好友);
         * buttonActiveStateMap.put(位置,真正的);
         * /        mViewHolder.addButton.setText(接受);
        mViewHolder.addButton.setEnabled(真);
    }    buttonTextMap.put(位置,mViewHolder.addButton.getText()的toString());
    Log.d(好友列表,在getview位置=====+位置);
    mViewHolder.addButton.setTag(位置);
    mViewHolder.addButton.setOnClickListener(新OnClickListener(){        公共无效的onClick(视图v){            其中INT = -1;
               obj对象= v.getTag();
              如果(OBJ的instanceof整数){
               其中=((整数)物镜).intValue();
               Log.e(FriendListActivity,位置按钮1 =======+其中);              }
              如果(这-1个){
                  Log.e(FriendListActivity,位置按钮2 =======+其中);
                }              Button按钮=(按钮)FriendListActivity.listView.getChildAt(所).findViewById(R.id.addFriendButton);            // Button按钮=(按钮)V;
            如果(button.getText()。的toString()。equalsIgnoreCase(接受)){
                意向意图=新意图(背景下,
                        NotificationsActivity.class);
                context.startActivity(意向);
                context.finish();
            }其他{
                INT ID = button.getId();
                addFriend(按钮,friendList.get(位置)
                        .getFriendUserId(),它);            }    }
    });
    返回convertView;
}静态类ViewHolder {
    TextView的FRIENDNAME;
    TextView的电子邮件;
    TextView的性别;    ImageView的profilePicture;
    按钮Add按钮;
}私人无效addFriend(最终按钮_button,最终字符串userid,
        最终诠释_position){
    最终的JSONObject的JSONObject =新的JSONObject();    Log.e(FriendListActivity,在addFriend位置===+ _position);    尝试{
        jsonObject.put(的authToken的authToken);
        jsonObject.put(targetFriendId,用户id);
        jsonObject.put(的RequestType,FriendRequest);
        jsonObject.put(状态,请求);    }赶上(JSONException E){
        // TODO自动生成catch块
        e.printStackTrace();
    }    最后的处理程序处理程序=新的处理程序(){        @覆盖
        公共无效的handleMessage(消息MSG){
            // TODO自动生成方法存根
            super.handleMessage(MSG);
            progressDialog.dismiss();
            如果(msg.what == 1){                _button.setText(请求发送);
                _button.setEnabled(假);
                Toast.makeText(背景下,请求发送成功。
                        Toast.LENGTH_LONG).show();
            }其他{
                Toast.makeText(上下文,请求unsuccessfull。
                        Toast.LENGTH_LONG).show();
            }        }
    };    progressDialog = ProgressDialog.show(背景下,,正在加载...);    新的Thread(){
        @覆盖
        公共无效的run(){            字符串的响应= DoFriendRequest
                    .makeHttpPostRequest(JSONObject的);
            消息消息=新的Message();
            如果(响应!= NULL){
                message.what = 1;
                handler.sendEmptyMessage(message.what);
            }其他{
                handler.sendEmptyMessage(0);
            }        }
    }。开始();}


解决方案

所以最后我找了很久的研究和理解完全ListView的回收和利用convertview后的解决方案。当我收到来自服务器的每个按钮的状态,所以在我addFriend()方法,我只是更新按钮的文本是pressed(仅视图),而不是从我在哪里名单获取数据的列表视图(列表视图中的每一行)。所以,我做什么,每当我更新按钮的标签状态为一排,我已经更新我的DataList控件(通过设置friendList.get(位置我的情况下好友列表).setFriendStatus(空))和呼叫转接器之后.notifyDatasetChanged()。我还忘了添加一个检查过滤器按钮的空状态。如果任何人有任何困惑,请问我。

这是我所提到的了解列表视图getView()链接于方法
     ListView的回收机制如何工作

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

}

解决方案

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

这篇关于列表视图定义适配器项目(按钮)的文本重复上滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆