Как динамически заполнять Android spinner текстом + изображение


Это то, что я пытаюсь достичь                       Я могу добиться этого:

screenshot           enter image description here


Мне удалось добавить текст и изображение в Spinner, но изображения не отображаются в раскрывающемся меню рядом с текстом. Его только отображается для выбранного элемента счетчика.

Вот мой код:

spinner_layout.xml
Макет, содержащий основной Spinner.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Spinner android:id="@+id/mySpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>


spinner_value_layout.xml
Макет элементов в Spinner. Это будет завышено с помощью адаптера.

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/spinnerTextView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <ImageView 
            android:id="@+id/spinnerImages"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@string/app_name"/>"

    </TableRow>

</TableLayout>


SpinnerActivity.java

package com.example.spinner;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.tempspinner.R;

public class SpinnerActivity extends Activity {

    String[] textArray = { "clouds", "mark", "techcrunch", "times" };
    Integer[] imageArray = { R.drawable.clouds, R.drawable.mark,
            R.drawable.techcrunch, R.drawable.times };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.spinner_layout);

        TextView text = (TextView) findViewById(R.id.spinnerTextView);
        ImageView imageView =(ImageView)findViewById(R.id.spinnerImages);
        Spinner spinner = (Spinner) findViewById(R.id.mySpinner);

        SpinnerAdapter adapter = new SpinnerAdapter(this, R.layout.spinner_value_layout, textArray, imageArray);
        spinner.setAdapter(adapter);

    }

}


SpinnerAdapter.java

package com.example.spinner;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.tempspinner.R;

public class SpinnerAdapter extends ArrayAdapter<String> {

    private Context ctx;
    private String[] contentArray;
    private Integer[] imageArray;

    public SpinnerAdapter(Context context, int resource, String[] objects,
            Integer[] imageArray) {
        super(context,  R.layout.spinner_value_layout, R.id.spinnerTextView, objects);
        this.ctx = context;
        this.contentArray = objects;
        this.imageArray = imageArray;
    }


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

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.spinner_value_layout, null);

        }

        TextView textView = (TextView) convertView.findViewById(R.id.spinnerTextView);
        textView.setText(contentArray[position]);

        ImageView imageView = (ImageView)convertView.findViewById(R.id.spinnerImages);
        imageView.setImageResource(imageArray[position]);

        return convertView;

    }

}

Ответ 1

Попробуйте это.

public class SpinnerAdapter extends ArrayAdapter<String> {

    private Context ctx;
    private String[] contentArray;
    private Integer[] imageArray;

    public SpinnerAdapter(Context context, int resource, String[] objects,
            Integer[] imageArray) {
        super(context,  R.layout.spinner_value_layout, R.id.spinnerTextView, objects);
        this.ctx = context;
        this.contentArray = objects;
        this.imageArray = imageArray;
    }

    @Override
    public View getDropDownView(int position, View convertView,ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.spinner_value_layout, parent, false);

        TextView textView = (TextView) row.findViewById(R.id.spinnerTextView);
        textView.setText(contentArray[position]);

        ImageView imageView = (ImageView)row.findViewById(R.id.spinnerImages);
        imageView.setImageResource(imageArray[position]);

        return row;    
    }    
}

Ответ 2

Попробуйте

Это самый простой способ создания счетчика с текстом и изображениями.

  • Создайте новый макет внутри res/layout/ с любым именем, например. spinner_value_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <TextView
            android:id="@+id/spinnerTextView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textColor="@color/colorBlack"/>
        <ImageView
            android:id="@+id/spinnerImages"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@string/app_name"/>"
    </TableRow>
    

  • Создайте новый класс SimpleImageArrayAdapter

     public class SimpleImageArrayAdapter extends ArrayAdapter<Integer> {
     private Integer[] images;
     private String[] text;
     private Context context;
    
     public SimpleImageArrayAdapter(Context context, Integer[] images,String[] text) {
       super(context, android.R.layout.simple_spinner_item, images);
       this.images = images;
       this.text=text;
       this.context=context;
     }
    
     @Override
     public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getImageForPosition(position, convertView, parent);
     }
    
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
         return getImageForPosition(position, convertView, parent);
     }
    
     private View getImageForPosition(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.spinner_value_layout, parent, false);
        TextView textView = (TextView) row.findViewById(R.id.spinnerTextView);
        textView.setText(text[position]);
        ImageView imageView = (ImageView)row.findViewById(R.id.spinnerImages);
        imageView.setImageResource(images[position]);
        return row;
       }
    
  • и, наконец, используйте это в своем классе, где вы передаете id spinner

     Integer[] integers=new Integer[]{R.drawable.ic_launcher_foreground, R.drawable.ic_launcher_background};
     String[] strings=new String[]{"foreground","background"};
    SimpleImageArrayAdapter adapter = new 
    SimpleImageArrayAdapter(getApplicationContext(),integers,strings);
      spinner.setAdapter(adapter);
    

Результат: - введите описание изображения здесь

Ответ 3

Spinner row.xml Вы можете удалить ненужные стили и образы с рисунком

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dip">

    <ImageView
        android:id="@+id/spinner_img"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/spinner_name"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="2dip"
        android:padding="3dip"
        android:textColor="@android:color/holo_red_dark" />
</LinearLayout>

Макет действий act_add_new_prog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Spinner
        android:id="@+id/spin_frag_four_kategori"
        android:layout_width="260dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="50dp"
        android:background="@drawable/aw_shadow"
        android:entries="@array/workouts"
        android:gravity="center|top|start"
        android:paddingLeft="15dp"
        android:text="Selam" />
</LinearLayout>

Класс действия

package com.sam.livehealty.addprogspinner;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Spinner;
import com.sam.livehealty.R;
import java.util.ArrayList;
public class AddNewProgramAct extends Activity {

    private ImageView img_back;
    private Spinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_add_new_prog);
        img_back = (ImageView) findViewById(R.id.img_act_add_new_program_back);
        spinner = (Spinner) findViewById(R.id.spin_frag_four_kategori);
        spinner.setAdapter(new MyAdapter(this, R.layout.spinner_row, getAllList()));

    }

    public ArrayList<ListItemAddProg> getAllList() {
        ArrayList<ListItemAddProg> allList = new ArrayList<ListItemAddProg>();
        ListItemAddProg item = new ListItemAddProg();
        item.setData("Brench Presses", R.drawable.ic_circling);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Incline Presses", R.drawable.ic_diamond);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Decline Presses", R.drawable.ic_personal);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Close-Grip Bench Presses", R.drawable.ic_team);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Dumbble Flys", R.drawable.ic_wrestling);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Incle Dumbbell Flys", R.drawable.ic_team);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Parallel Bar Dips", R.drawable.ic_personal);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Dumbble Flys", R.drawable.ic_circling);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Incline Dumbble Flys", R.drawable.ic_team);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Parallel Bar Dips", R.drawable.ic_circling);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Barbell Pullovers", R.drawable.ic_wrestling);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Peck  Deck Flyes", R.drawable.ic_team);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Peck  Deck Flyes", R.drawable.ic_personal);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData(" Incline Dumbbell  Presses", R.drawable.ic_circling);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Cable Crossover Flyes", R.drawable.ic_wrestling);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Machine Bench Press", R.drawable.ic_team);
        allList.add(item);
        item = new ListItemAddProg();
        item.setData("Push-Ups", R.drawable.ic_personal);
        allList.add(item);

       /* for (int i = 0; i < 10000; i++) {
            item = new ListItemAddProg();
            item.setData("Google " + i + i, R.drawable.ic_remove);
            allList.add(item);
        }*/

        return allList;
    }
}

ItemModel для каждой строки

public class ListItemAddProg {
    String name;
    int logo;
    public void setData(String name, int logo) {
        this.name = name;
        this.logo = logo;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getLogo() {
        return logo;
    }
    public void setLogo(int logo) {
        this.logo = logo;
    }
}

И класс адаптера

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sam.livehealty.R;
import java.util.ArrayList;

public class MyAdapter extends ArrayAdapter<ListItemAddProg> {
    LayoutInflater inflater;
    ArrayList<ListItemAddProg> objects;
    ViewHolder holder = null;

    public MyAdapter(Context context, int textViewResourceId, ArrayList<ListItemAddProg> objects) {
        super(context, textViewResourceId, objects);
        inflater = ((Activity) context).getLayoutInflater();
        this.objects = objects;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {
        ListItemAddProg listItemAddProg = objects.get(position);
        View row = convertView;
        if (null == row) {
            holder = new ViewHolder();
            row = inflater.inflate(R.layout.spinner_row, parent, false);
            holder.name = (TextView) row.findViewById(R.id.spinner_name);
            holder.img = (ImageView) row.findViewById(R.id.spinner_img);
            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();
        }
        holder.name.setText(listItemAddProg.getName());
        holder.img.setBackgroundResource(listItemAddProg.getLogo());
        return row;
    }

    static class ViewHolder {
        TextView name;
        ImageView img;
    }
}