简体   繁体   中英

Android populate ListView with array colors

I want to populate the ListView with an array of RGB colors. That is, each line must take the RGB color assigned. Is it possible?

public class Lista_colori extends Activity {

    // Initialize the array
    String[] Array = { "#33B5E5", "#d8e1e4", "#000000" };

    // Declare the UI components
    private ListView monthsListView;

    private ArrayAdapter arrayAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.colori);

        // Initialize the UI components
        monthsListView = (ListView) findViewById(R.id.listView1);

        // From the third parameter, you plugged the data set to adapter
        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, Array);

        // By using setAdapter method, you plugged the ListView with adapter
        monthsListView.setAdapter(arrayAdapter);

    }
}

you can create one custom adapter and use getview method for this - it would be the best to sav the colors as resources and do this:

monthsListView = (ListView) findViewById(R.id.listView1);
CustomAdapter adapter = new CustomAdapter(this, list);
monthsListView.setAdapter(adapter);

public class CustomAdapter extends BaseAdapter {

        List<String> colorList;

        public CustomAdapter(Activity activity, List<String> colorList) {
            // TODO Auto-generated constructor stub
            this.colorList = productList;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return this.colorList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }



        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            // TODO Auto-generated method stub


switch(position){
case 1:
   view.setBackgroundColor(R.colors.color_one);break;
case 2: //etc..
}

            });
            return convertView;
        }

    }

This is just a snippet, try to modify this as per your requirement.

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