Custom Android ArrayAdaper: Alternate background color for elements in ArrayAdapter
This ColorArrayAdapter extends ArrayAdapter, sets alternating color for each view in the created ArrayAdapter. In the getView method, it can be customized more.
import android.content.Context; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class ColorArrayAdapter extends ArrayAdapter<Object>{ private String[] list; public ColorArrayAdapter(Context context, int textViewResourceId, Object[] objects) { super(context, textViewResourceId, objects); list = new String[objects.length]; for (int i = 0; i < list.length; i++) list[i] = (String) objects[i]; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = (TextView)super.getView(position, convertView, parent); if(position%2==0) { view.setBackgroundColor(Color.parseColor("#FFD700")); } return view; } }
The code below demonstrates how to use the above custom ArrayAdpter in a ListFragment, in the onCreate method.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We need to use a different list item layout for devices older than Honeycomb int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1; String[] items = { "view 1", "view 2", "view 3", "view 4", "view 5", "view 6", "view 7", "view 8", "view 9"}; // Create an array adapter for the list view, using the Ipsum headlines array setListAdapter(new ColorArrayAdapter(getActivity(), layout, items)); }
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts