开发者

adding an image to listview, the listview is present in the tabwidget

开发者 https://www.devze.com 2023-04-06 14:15 出处:网络
I have 4 tabs A,B,C and D. Each tab has a listview in it 开发者_如何学Gowhich I\'m populating using the following code:

I have 4 tabs A,B,C and D. Each tab has a listview in it 开发者_如何学Gowhich I'm populating using the following code:

 TabSpec s1=tabhost1.newTabSpec("Tab A");
 s1.setIndicator("A",getResources().getDrawable(R.drawable.A));
 s1.setContent(R.id.listV1);
 tabhost1.addTab(s1);

 listview1= (ListView) findViewById(R.id.listV1);
 listview1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.tab1content)));

Now I want to add an image for each of the item in the listview, any leads on how do I go about in doing it?


This works for me :

class ListAdapter extends BaseAdapter {

    public int getCount() {  //returns the size of your list
        if (imgDetails != null) {
            return imgDetails.size();
        }
        return 0;
    }
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }
    public View getView(int arg0, View convertView, ViewGroup arg2) {
        if (convertView == null) {
            convertView =  getLayoutInflater().inflate(R.layout.details_cell_view, null); // create an xml to inflate and put an imageview , textview in it.
        }
        String str = imgDetails.get(arg0).getId();
        if(str.equals("1"))
            ((ImageView) convertView.findViewById(R.id.img_details_img)).setBackgroundResource(R.drawable.img_1);
        if(str.equals("2"))
            ((ImageView) convertView.findViewById(R.id.img_details_img)).setBackgroundResource(R.drawable.img_2);
        if(str.equals("3"))
            ((ImageView) convertView.findViewById(R.id.img_details_img)).setBackgroundResource(R.drawable.img_3);
        if(str.equals("4"))
            ((ImageView) convertView.findViewById(R.id.img_details_img)).setBackgroundResource(R.drawable.img_4);


        ((TextView) convertView.findViewById(R.id.img_details_txt)).setText(imgDetails.get(arg0).getText());
       //to set an arrow at the right of each row
        ((ImageView) convertView.findViewById(R.id.right_arrow)).setBackgroundResource(R.drawable.arrow_img);
        convertView.setPadding(1, 1, 1, 0);
        return convertView;
    }

}


Create a custom ListAdapter where you will set the images to list items. Set this adapter as the ListAdapter for this list using

ListView listView = (ListView) findViewById(R.id.listV1);
listView.setAdapter(new CustomListAdapter(this));

Check this tutorial on how to create Custom Adapters http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/

0

精彩评论

暂无评论...
验证码 换一张
取 消