'Scrolling ListView
In listView I marked a line selected by a particular color, scrolling down the list and going back up - a marked line becomes colored even though there is still a mark (I did a test for it). Have you encountered such a phenomenon and if so how can you handle it.
''' public class CustomDesignList extends AppCompatActivity {
ArrayList<Fruit> list;
ListView listView;
FruitAdapter adapter;
String[] fruitNames= {"apple", "apricot", "banana", "cherry", "coconut", "grapes",
"kiwi","mango", "melon","orange", "peach","pear",
"pineapple","strawberry", "watermelon"};
int[] imageResourceArray= {R.drawable.apple,R.drawable.apricot,R.drawable.banana,
R.drawable.cherry,R.drawable.coconut,R.drawable.grapes,
R.drawable.kiwi,R.drawable.mango,R.drawable.melon,R.drawable.orange,
R.drawable.peach,R.drawable.pear,R.drawable.pineapple,
R.drawable.strawberry,R.drawable.watermelon};
int[] arrCounter=new int[15];// מערך מונים לסימון ברשימה
int sum=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_design_list);
for(int i = 0; i< arrCounter.length;i++)
arrCounter[i] = 0;
listView=findViewById(R.id.lvCustom);
list=new ArrayList<>();
for(int i=0; i<fruitNames.length;i++)
list.add(new Fruit(fruitNames[i],
(int)((Math.random() * (100 - 10 + 1)) + 10),
imageResourceArray[i]));
//Connect all data to all elements in the list
//Layout where we defined what one element in the list would look like
adapter=new FruitAdapter(this,R.layout.my_custom_list,this.list);
//Connect the full list of data to xml
this.listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
arrCounter[position]++;
if( arrCounter[position] %2==1)
{
view.setBackgroundColor(Color.parseColor("#EBBEF3"));
sum+=list.get(position).getFruitWeight();//
}
else
{
view.setBackgroundColor(Color.TRANSPARENT);
sum-=list.get(position).getFruitWeight();//
}
}
});
}'''
Solution 1:[1]
You have a bunch of problems here.
1)You shouldn't be using ListView these days. RecyclerView replaced it most of a decade ago.
2)In a ListView click handler, you can't change anything in the UI. If you do and you don't really know what you're doing, you're going to screw it up. Like you did here. Instead of changing the UI, you should change the data in the adapter, and then tell the view to reload new data from the adapter. Anything else and you're going to have problems when the views recycle themselves on scroll.
I'd really look at changing to recycler view, but at a minimum you need to change how your click handler works completely so that it doesn't make any UI changes directly and only changes the data.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gabe Sechan |
