Create spinner without <Spinner in xml

2019-08-10 02:15发布

问题:

I was using a spinner in a TableRow and it was working perfectly well except that I didn't like spinner icon is stretching out according to the selected item. I tried to delete Spinner section in xml and create it on my code.

To create a spinner in OnCreate():

selectArea = /*(Spinner)this.findViewById(R.id.spinner);*/new Spinner(this);

String[] ss = getResources().getStringArray(R.array.countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ss);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

selectArea.setOnItemSelectedListener(new MyOnItemSelectedListener());
selectArea.setSelection(prefInt);

To handle a selection event:

public class MyOnItemSelectedListener implements OnItemSelectedListener {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        Log.d(TAG, "onItemSelected() " + id);
    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Do nothing.
    }
}

It worked almost perfect. TableRow show no spinner icon, on touching TableRow, it pops up items to be selected. My only problem is that, on selecting one tiem, I never get my onItemSelected() called..
What could be wrong?

回答1:

please change this line

spinner.setAdapter(adapter);

into the line

selectedArea.setAdapter(adapter);


回答2:

see i have created spinner here

 Spinner selectArea= new Spinner(Activity.this);
     String[] ss = getResources().getStringArray(R.array.countries);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ss);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    selectArea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    selectArea.setAdapter(adapter);              
    linearLayout1.addView(selectArea);//to add your spinner
    selectArea.setOnItemSelectedListener(new MyOnItemSelectedListener());