kapad
kapad

Reputation: 651

android spinner and array adapter programmatically

I am trying to programmatically create a Spinner using an ArrayAdapter. This is being done in a closed source jar as part of an Android library project and I do not have any access to resources.

I want to know how to customize the layout and the text view that displays the spinner.

--EDIT--
Presently I am using the following code

ArrayAdapter<T> spinnerData = new ArrayAdapter<T>(this, Android.R.layout.simple_spinner_item, T[]);

spinner.setAdapter(spinnerData);

What is happening is that I cannot control the size of the fonts, colours or anything else. When I click on the spinner to select something all the options are in really small text. I want to be able to change the way it renders on screen.

Upvotes: 9

Views: 30411

Answers (1)

user936414
user936414

Reputation: 7634

Just create a custom ArrayAdapter and define how the spinner textview should look in that getDropDownView method of the adapter

public class CustomizedSpinnerAdapter extends ArrayAdapter<String> {

 private Activity context;
 String[] data = null;

 public CustomizedSpinnerAdapter(Activity context, int resource, String[] data2)
 {
     super(context, resource, data2);
     this.context = context;
     this.data = data2;
 }
  ...

 @Override
 public View getDropDownView(int position, View convertView, ViewGroup parent)
 {   
     View row = convertView;
     if(row == null)
     {
         //inflate your customlayout for the textview
         LayoutInflater inflater = context.getLayoutInflater();
         row = inflater.inflate(R.layout.spinner_layout, parent, false);
     }
     //put the data in it
     String item = data[position];
     if(item != null)
     {   
        TextView text1 = (TextView) row.findViewById(R.id.rowText);
        text1.setTextColor(Color.WHITE);
        text1.setText(item);
     }

     return row;
 }
...
}

and set this adapter for the spinner

Spinner mySpinner = (Spinner) findViewById(R.id.mySpinner);
final String[] data = getResources().getStringArray(
            R.array.data);
final ArrayAdapter<String> adapter1 = new CustomizedSpinnerAdapter(
            AddSlaveActivity.this, android.R.layout.simple_spinner_item,
            data);
mySpinner.setAdapter(adapter1); 

Upvotes: 16

Related Questions