I use BaseAdapter for my listview. I have following code:
public class ListViewAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<JSONObject> arrayList;
private GetterSetter getterSetter = new GetterSetter();
public ListViewAdapter(Context context, ArrayList arrayList, Bundle bundle) {
this.mContext = context;
this.arrayList = arrayList;
this.bundle = bundle;
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(R.layout.list_item, null);
}
TextView nameTextView = convertView.findViewById(R.id.textview_book_name);
LinearLayout linearLayout = convertView.findViewById(R.id.item);
JSONObject jsonObject = arrayList.get(position);
try {
String title = jsonObject.getString("title");
String _id = jsonObject.getString("_id");
nameTextView.setText(title);
if(getterSetter.ifExists(_id)){
linearLayout.setBackgroundColor(Color.parseColor("#397EAD"));
nameTextView.setTextColor(Color.WHITE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
}
ifExists method in GetterSetter Class:
public Boolean ifExists(String _id){
if (myList != null) {
for (int i=0;i<myList.size();i++){
try {
JSONObject jsonObject = myList.get(i);
if(_id.equals(jsonObject.getString("_id"))){
return true;
}
} catch (JSONException e){}
}
}
return false;
}
Layout for item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/item" >
<TextView
android:id="@+id/textview_book_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="35dp"
android:textSize="18sp"
android:textColor="#000000" />
My listview work well but if I scrolling it, each item changing color suddenly. I want that items have a RGB Color: #397EAD if his _id exists in static ArrayList in another class. How can I do that? How can I resolve a problem with changing color when I scrolling?
You're not handling convertView
recycling. You're setting the colors if it exists in the list, but you need an else
block to set them back to the defaults if it doesn't exist in the list:
if(getterSetter.ifExists(_id)){
linearLayout.setBackgroundColor(Color.parseColor("#397EAD"));
nameTextView.setTextColor(Color.WHITE);
} else {
// reset linearLayout and nameTextView colors to default here
}