Android Listview - Change Item Button Text After C

2019-09-09 20:50发布

问题:

I am trying to convert my app to android version, and I am a bit new in android. I have a list view in which the items include buttons. It is a user list and you can follow each user, when the button is clicked, only in the item including the button, the button text should turn in to "followed". Retrieving the list works fine, but with my below code the button text is not changing. How can I make this happen? Thank you very much.

private class MyListAdapter extends ArrayAdapter<String>  {
    public MyListAdapter() {
        super(getActivity().getApplicationContext(), R.layout.fragment_users_cell, myItemList);
    }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View cellView = convertView;

            if (cellView == null){
                cellView = getActivity().getLayoutInflater().inflate(R.layout.fragment_users_cell, parent, false);
            }

            profileBtn = (Button) cellView.findViewById(R.id.fragment_users_cell_profileBtn);
            followBtn = (Button) cellView.findViewById(R.id.fragment_users_cell_followBtn);

            profileBtn.setText(myItemList.get(position));


            profileBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    System.out.println(myItemList.get(position));

                    System.out.println(position);

                }
            });


            followBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    System.out.println(myItemList.get(position));

                    profileBtn.setText("followed");

                }
            });



            return cellView;

        }

    }

回答1:

You have to update your dataset and refersh the list after you make changes so that it reflects the latest changes. In your case the text changes.

followBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  profileBtn.setText("followed");
                  myItemList.add(position, "followed");//Change your dataset
                  notifyDataSetChanged();  //And refresh the adapter    
                }
            });


回答2:

you need to change the value in myItemList so that next time when view load, the value from list set as text on profile button comes which ix followed i.e. you need to update the list on click of follow button and notify the ListView.

followBtn.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View v) {
        System.out.println(myItemList.get(position));
        myItemList.get(position).set("followed");
        profileBtn.setText("followed");
    }
});