0

所以我正在编写一个包含三个微调器的程序,我想为每个微调器添加一个数组。但是,我目前拥有的代码可以工作,但很长,所以我想知道是否有更简单/更短/更有效的编码方式。

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.distanceType,
                android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        distanceSpinner.setAdapter(adapter);

        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
                this, R.array.areaType, android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        areaSpinner.setAdapter(adapter2);

        ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(
                this, R.array.genderType, android.R.layout.simple_spinner_item);
        adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        genderSpinner.setAdapter(adapter3);

正如你所看到的,它基本上是相同的代码重复了 3 次。

4

1 回答 1

3

创建一个工厂方法来简化您的自定义适配器的编写:

 public ArrayAdapter createSimpleAdapter(int itemsArrayId ) {
       ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, itemsArrayId,
            android.R.layout.simple_spinner_item);
       adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
       return adapter;         
 }

然后创作变得如此简单:

 distanceSpinner.setAdapter(createSimpleAdapter(R.array.distanceType));
 areaSpinner.setAdapter(createSimpleAdapter(R.array.areaType));
 genderSpinner.setAdapter(createSimpleAdapter(R.array.genderType));
于 2013-05-06T20:44:02.450 回答