简体   繁体   中英

Scrolling down the ListView the favourite button checked gets unchecked android studio

The code below saves the current text of the TextView when the favourite button is clicked and the button Image changes to Fav_Checked when I click again the favourite button is unchecked and the text in array is removed but the issue is when I scroll down the ListView updates and the favourite buttons are unchecked. kindly help.

public class MainActivity extends AppCompatActivity {

//     ArrayList<String> names = new ArrayList<>();
    private ArrayList<String> names;
    int x = names.size();
//    private boolean[x] favorites;
    private SharedPreferences sharedPreferences;

    Context context = this;
    MediaPlayer mPlayer;
    Boolean isPlay = true;
    ImageView playPauseGlobelBtn;
    int maxVolume,resID,position;
    String fname;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         ListView listView=(ListView)findViewById(R.id.listView);
        mPlayer = MediaPlayer.create(context, R.raw.asdf);
        CustomAdapter customAdapter=new CustomAdapter();
        listView.setAdapter(customAdapter);

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");

        if(favoriteItems.isEmpty()) {
            names = new ArrayList<>();
        }
        else {
            names = new ArrayList<>(Arrays.asList(favoriteItems.split(",")));
        }
    }
    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        view = getLayoutInflater().inflate(R.layout.customlayout, null);
         final TextView textView_name = (TextView) 
        view.findViewById(R.id.textView_name);
         final Button favoritebutton = (Button) view.findViewById(R.id.tgbFav);
         buttonInfo.setOnClickListener(new View.OnClickListener() {
                 String tag = v.getTag().toString();
                if(tag != null) {
                    int i = Integer.parseInt(tag);
                    System.out.println(tag);
                 }
            }
        });


private ArrayList<String> names;
private SharedPreferences sharedPreferences;

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");

 if(favoriteItems.isEmpty())
    names = new ArrayList<>();
    else
      names = new ArrayList<>(Arrays.asList(favoriteItems.split(","));  //Update like this

      favoritebutton.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick( View v) {
        if (!names.contains(textView_name.getText())){
            names.add((String) textView_name.getText());

            for (int i=0; i<names.size(); i++) {
                System.out.println(names.get(i));
                favoritebutton.setBackgroundResource(R.drawable.fav_checked);
            }
        }
        else {
            System.out.println(textView_name.getText() + "   is already present in the Array at index " + names.indexOf(textView_name.getText()));
            int currentIndex = names.indexOf(textView_name.getText());
            names.remove(currentIndex);
            for (int i=0; i<names.size(); i++) {
                System.out.println(names.get(i));
                favoritebutton.setBackgroundResource(R.drawable.star_off);
            }
        }

        sharedPreferences.edit().putString("FAVORITE_ITEMS", TextUtils.join(",", names)).apply();
    }
});

 <ToggleButton
        android:id="@+id/tgbFav"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:focusable="false"
        android:focusableInTouchMode="false"

        android:textOff=""
        android:layout_toLeftOf="@+id/button"
        android:textOn=""/>

When you scroll the ListView , the few visible view items will be reused for the entire list. If you aren't handling the getView correctly, the item that was previously used for a name without favorite will be reused for a name that is set as favorite. Hence, it will look like the favorite button gets unchecked while scrolling the ListView . You have to keep track of the favorite status of all the names and use it in getView to show the proper UI.

Now, when the favoritebutton is clicked, you are updating it's background, and updating the ArrayList "names". You need to use this ArrayList in your getView , check the current favorite status of the name, and use that to set the proper background resource for the favoritebutton in your getView .

Mate, what i have get from your question and snippet you post is you're saving all the favourite item name in shared-preference. But as you know you get that 'FAVORITE_ITEMS' in onCreate so it will only provide you the previously added favourite item. And in your you know if your scroll list view the item get update because getView() called for every item as such your favourite item that you clicked only seems as favourite until you didn't scroll list. For showing that item you need to check your item is present in favourite items or not for that add this snippet in your getView()

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {

  Your code.... 

  String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");  
  if (favoriteItems.contains(textView_name.getText())) {
      favoritebutton.setBackgroundResource(R.drawable.fav_checked);
  } else {
      favoritebutton.setBackgroundResource(R.drawable.star_off);
  }

  ....

}

Remember to notify list when any favouriteButton clicked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM