0

I have a Spinner and I am using an ArrayAdapter to populate it. I want to be able to show the custom object's fields inside each spinner item:

spinner with custom object fields

The image looks a bit blurred but it contains "Savings", "account number", and Balance as fields of the Custom Objects.

How can I show it exactly like that?

Jepoy
  • 77
  • 1
  • 1
  • 15
  • 1
    refer this [example](http://www.zoftino.com/android-spinner-custom-adapter-&-layout) – Rutvik Bhatt Jun 18 '18 at 06:45
  • Possible duplicate of [How to customize a Spinner in Android](https://stackoverflow.com/questions/16694786/how-to-customize-a-spinner-in-android) – Reaz Murshed Jun 18 '18 at 06:49

1 Answers1

0
  1. Create your custom XML layout file (in your app/res/layout/ folder) for a spinner item

    This should contain 3 TextView's , with each TextView displaying the fields of your custom object (so 1 TextView for "Savings", 1 for "account number" and another for "balance". You can, of course, modify these depending on your custom object.

  2. Create a custom Adapter class that extends from ArrayAdapter<String>

    You will need to override both getView() and getDropDownView() to inflate the Spinner with your newly created layout.

    @Override
    public @NonNull View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    
        final View view = mInflater.inflate(R.layout.my_custom_spinner_item, parent, false);
    
        TextView savingsTV = (TextView) view.findViewById(R.id.tv_savings);
        TextView accountNumberTV = (TextView) view.findViewById(R.id.tv_account_number);
        TextView balanceTV = (TextView) view.findViewById(R.id.tv_balance);
    
        CustomObject object = objectsList.get(position);
    
        // Format your fields to strings here
        savingsTV.setText(object.getSavings());
        accountNumberTV.setText(object.getAccountNumber());
        balanceTV.setText(object.getBalance());
    
        return view;
    }
    
  3. Set up your custom adapter's list to your List<CustomObject> in Activity

    spinner = (Spinner) findViewById(R.id.spinner);
    CustomArrayAdapter adapter = new CustomArrayAdapter(this, getList());
    spinner.setAdapter(adapter);
    

Here is a good example on how it is made.

Fawwaz Yusran
  • 1,260
  • 2
  • 19
  • 36