如何使用Image数组创建数组适配器

时间:2015-04-25 14:21:56

标签: java android

我有2个数组,如:

数组1:

String[] web = {"Google Plus","Twitter","Windows","Bing","Itunes","Wordpress","Drupal"} ;

数组2:

String[] webimage = {"@drawable/img1","@drawable/img2","@drawable/img3","@drawable/img4","@drawable/img5","@drawable/img6","@drawable/img7"} ;

我想创建ArrayAdapter使用我的Array1作为TextView并使用Array2作为行的图标

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.single_row,R.id.textView,array);

1 个答案:

答案 0 :(得分:0)

您可以创建一个类来保存String和可绘制资源

public class Item{

    private final String text;
    private final int icon;

    public Item(final String text, final int icon){
        this.text = text;
        this.icon = icon;
    }

    public String getText(){
        return text;
    }

    public Drawable getIcon(final Context context){
        return context.getResources().getDrawable(this.icon)
    }
}

然后创建一个Items数组

Item[] items = new Item[1];
item[0] = new Item("Google Plus",R.drawable.img1);
//...etc

为Item

创建自定义ArrayAdapter
public class ItemAdapter extends ArrayAdapter<Item> {

    private Context context;

    public ItemAdapter(Context context, Item[] items) {
        super(context, 0, items);

        this.context = context;
     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {

        // Get the data item for this position
        Item item = getItem(position);    

        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
           convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_row, parent, false);
        }

        // Lookup view for data population
        TextView tvText = (TextView) convertView.findViewById(R.id.tvText);
        ImageView ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);

        // Populate the data into the template view using the data object
        tvText.setText(item.getText());
        ivIcon.setImageDrawable(item.getDrawable(this.context));

        // Return the completed view to render on screen
        return convertView;
    }
}

在上面的示例中,R.layout.item_row是您必须创建的布局,其中包含ID为TextView的{​​{1}}和ID为tvText的ImageView。