Thursday, February 6, 2020

How to custom Spinner in Android with image and text

Step 1. Custom layout spinner in Android
In this step, we will create layout file that will represent the spinner’s view.
How to custom Spinner in Android with image and text

So, make a new layout resource file named spinner_custom_layout.xml
Add below source code in it.
<?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">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:padding="5dp"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_gravity="center"
        android:text="Custom Text"
        android:textColor="#000" />

</LinearLayout>
Step 2. Download image in google internet or in computer of your.
Now add these images into res-> drawable folder.
Step 3. Custom adapter
We need to write custom adapter that will accept our custom layout file.
This adapter will create the custom view for our spinner using that spinner_custom_layout.xml file.
Following source code is for CustomAdapter.java file.
public class CustomAdapter extends BaseAdapter {
    Context context;
    int images[];
    String[] fruit;
    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, int[] flags, String[] fruit) {
        this.context = applicationContext;
        this.images = flags;
        this.fruit = fruit;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return images.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.spinner_custom_layout, null);
        ImageView icon = (ImageView) view.findViewById(R.id.imageView);
        TextView names = (TextView) view.findViewById(R.id.textView);
        icon.setImageResource(images[i]);
        names.setText(fruit[i]);
        return view;
    }
}
Step 4. Create layout activity main
In this last step, you should update the code of your activity_main.xml and MainActivity.java file code
Replace the code of activity_main.xml with the below one
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

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

</LinearLayout>
Step 5. Create class MainActivity.java
public class MainActivity extends AppCompatActivity {

    String[] fruits={"Apple","Grapes","Mango","Pineapple","Strawberry"};
    int images[] = {R.drawable.apple,R.drawable.grapes, R.drawable.mango, R.drawable.pineapple, R.drawable.strawberry };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Getting the instance of Spinner and applying OnItemSelectedListener on it
        Spinner spin = (Spinner) findViewById(R.id.spinner);
        spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "You Select Position: "+position+" "+fruits[position], Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        CustomAdapter customAdapter=new CustomAdapter(getApplicationContext(),images,fruits);
        spin.setAdapter(customAdapter);
    }
}
Explanation of Above Code
Look at the below two lines
String[] fruits={"Apple","Grapes","Mango","Pineapple","Strawberry"};
int images[] = {R.drawable.apple,R.drawable.grapes, R.drawable.mango, R.drawable.pineapple, R.drawable.strawberry };
First line defines the string array. This string array includes the names of the fruits.
Second line defines the integer array which includes the resource id of the images which we have inserted in the drawable folder.
  CustomAdapter customAdapter=new CustomAdapter(getApplicationContext(),images,fruits);
  spin.setAdapter(customAdapter);
Above code will first define the object of the adapter class and then compiler will set the adapter to the spinner in android.
We have to pass out string and integer arrays as a parameter when defining the object of the adapter.
After this, our spinner will be populated with images and texts.
To track the on click method of the spinner, read below code
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "You Select Position: "+position+" "+fruits[position], Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });