2015-04-25 2 views
-1

У меня есть 2 массивы, такие как:Как создать адаптер массива с массивом Image

массив 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, который использует мой массив 1 для TextView и использует Array2 для значка строки

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

Что вы хотите сказать? Вы можете уточнить? – Jost

+0

Вместо использования Array2 используйте отражение. –

+0

@Jost: Я хочу создать адаптер массива, чтобы каждая строка отображала изображение в Array1 и текст в Array2 –

ответ

0

Вы могли бы создать класс для хранения строки и рисуем ресурс

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) 
    } 
} 

, а затем создать массив элементов

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

создания пользовательского 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 - это макет, который вам нужно будет создать, содержащий TextView остроумие h id tvText и ImageView с идентификатором ivIcon.

Смежные вопросы