Skip to content

Instantly share code, notes, and snippets.

@wightwulf1944
Created January 19, 2018 03:37
Show Gist options
  • Save wightwulf1944/123ef278b8b0e93a6d4424c96339bc13 to your computer and use it in GitHub Desktop.
Save wightwulf1944/123ef278b8b0e93a6d4424c96339bc13 to your computer and use it in GitHub Desktop.
public class MainActivity extends AppCompatActivity {
ListView listView;
MyAdapter adapter;
List<MyData> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
data = new ArrayList<>();
data.add(new MyData("123", Color.GREEN));
data.add(new MyData("456", Color.RED));
data.add(new MyData("789", Color.BLUE));
adapter = new ArrayAdapter<>(this, /* your layout here */, data);
listView.setAdapter(adapter);
}
// this method sets the color of a certain item and notifies the adapter that that the data has changed
public void setColor(int position, int color) {
MyData item = data.get(position);
item.setColor(color);
adapter.notifyDataSetChanged();
}
}
public class MyAdapter extends BaseAdapter {
private LayoutInflater inflater;
private int layoutResource;
private List<MyData> data;
public MyAdapter(Context context, int layoutResource, List<MyData> data) {
inflater = LayoutInflater.from(context);
this.data = data;
this.layoutResource = layoutResource;
}
@Override
public int getCount() {
return data.size();
}
@Override
public MyData getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = createView(convertView, parent);
MyData data = getItem(position);
// TO DO: setup your view here such as setting the color, and the text
return view;
}
private View createView(View convertView, ViewGroup parent) {
if (convertView == null) {
return inflater.inflate(layoutResource, parent, false);
} else {
return convertView;
}
}
public static class MyData {
private final String value;
private final int color;
public MyData(String value, int color) {
this.value = value;
this.color = color;
}
public void setColor(int color) {
this.color = color;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment