开发者

the setAdapter method on a Spinner object - Do we always need to implement it as an extension of ArrayAdapter?

开发者 https://www.devze.com 2023-02-16 10:01 出处:网络
Consider the following code, which is a simple way of defining a spinner with data from an Array backing its function:

Consider the following code, which is a simple way of defining a spinner with data from an Array backing its function:

public class HelloAndroid extends Activity implements AdapterView.OnItemSelectedListener {
    Spinner myspinner;
    ArrayAdapter<String> myadapter;
    final String[] sample_data={"Sankar", "Sunita", "Hari", "Susha", "Lovely"};

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        myspinner=(Spinner)findViewById(R.id.myspinner);
        myadapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,sample_data);
        myadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        myspinner.setOnItemSelectedListener(this);
        myspinner.setAdapter(myadapter);
    }

    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Toast.makeText(this, myadapter.getItem(arg2), Toast.LENGTH_SHORT).show();
    }

    public void onNothingSelected(AdapterView<?> arg0) {
        Toast.makeText(this, "Nothing Selected", Toast.LENGTH_SHORT).show();
    }
}

My point here is that in order to implement the spinner, I am having to use an ArrayAdapter. Can't I associate the Spinner direc开发者_运维问答tly with an implementation of SpinnerAdapter? SpinnerAdapter does not have a setDropDownViewResource method like ArrayAdapter, so how would we set the drop down view resource that should show on the spinner? I'm am confused on how SpinnerAdapter is serving its purpose as an adapter for a Spinner when it cannot provide the two view (field and dropdown) that the spinner requires?

Any help is appreciated.


SpinnerAdapter is an interface and so only defines a set of methods which are required to support a Spinner.

ArrayAdapter is a class, and implements the SpinnerAdapter interface methods along with other functionality to actually provide a working implementation.

You can write your own class which implements the methods from the SpinnerAdapter interface to show what you want to show in a drop down, but as SpinnerAdapter contains no code, you can't use the SpinnerAdapter itself.

The best way to think of it is SpinnerAdapter tells you what you need to do (as it is an interface), and ArrayAdapter actually does it (because it is a class).

0

精彩评论

暂无评论...
验证码 换一张
取 消