使用数组列表的Android Spinner数据绑定

时间:2011-07-03 10:07:01

标签: android data-binding arraylist spinner android-arrayadapter

我有一个像这样的数组列表:

private ArrayList<Locations> Artist_Result = new ArrayList<Location>();

此Location类有两个属性:idlocation

我需要将ArrayList绑定到微调器上。我试过这种方式:

Spinner s = (Spinner) findViewById(R.id.SpinnerSpcial);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, Artist_Result);
s.setAdapter(adapter);

但是,它显示了对象的十六进制值。所以我想我必须设置显示该微调控制器的文本和值。

5 个答案:

答案 0 :(得分:38)

ArrayAdapter尝试通过调用Object.toString()-method将您的Location - 对象显示为字符串(导致十六进制值)。它的默认实现返回:

  

[...]一个字符串,由类的名称组成   是一个实例,符号字符`@'和无符号   对象哈希码的十六进制表示。

要使ArrayAdadpter在项目列表中显示实际有用的内容,您可以覆盖toString() - 方法以返回有意义的内容:

@Override
public String toString(){
  return "Something meaningful here...";
}

另一种方法是,以扩展BaseAdapter 实现SpinnerAdapter来创建自己的适配器,它知道中的元素您的ArrayList是对象以及如何使用这些对象的属性。

[修订]实施例

我玩了一下,我设法得到了一些工作:

public class Main extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Create and display a Spinner:
        Spinner s = new Spinner(this);
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
        );
        this.setContentView(s, params);
        // fill the ArrayList:
        List<Guy> guys = new ArrayList<Guy>();
        guys.add(new Guy("Lukas", 18));
        guys.add(new Guy("Steve", 20));
        guys.add(new Guy("Forest", 50));
        MyAdapter adapter = new MyAdapter(guys);
        // apply the Adapter:
        s.setAdapter(adapter);
        // onClickListener:
        s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            /**
             * Called when a new item was selected (in the Spinner)
             */
            public void onItemSelected(AdapterView<?> parent,
                                       View view, int pos, long id) {
                Guy g = (Guy) parent.getItemAtPosition(pos);
                Toast.makeText(
                        getApplicationContext(),
                        g.getName()+" is "+g.getAge()+" years old.",
                        Toast.LENGTH_LONG
                ).show();
            }

            public void onNothingSelected(AdapterView parent) {
                // Do nothing.
            }
        });
    }

    /**
     * This is your own Adapter implementation which displays
     * the ArrayList of "Guy"-Objects.
     */
    private class MyAdapter extends BaseAdapter implements SpinnerAdapter {

        /**
         * The internal data (the ArrayList with the Objects).
         */
        private final List<Guy> data;

        public MyAdapter(List<Guy> data){
            this.data = data;
        }

        /**
         * Returns the Size of the ArrayList
         */
        @Override
        public int getCount() {
            return data.size();
        }

        /**
         * Returns one Element of the ArrayList
         * at the specified position.
         */
        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }
        /**
         * Returns the View that is shown when a element was
         * selected.
         */
        @Override
        public View getView(int position, View recycle, ViewGroup parent) {
            TextView text;
            if (recycle != null){
                // Re-use the recycled view here!
                text = (TextView) recycle;
            } else {
                // No recycled view, inflate the "original" from the platform:
                text = (TextView) getLayoutInflater().inflate(
                        android.R.layout.simple_dropdown_item_1line, parent, false
                );
            }
            text.setTextColor(Color.BLACK);
            text.setText(data.get(position).name);
            return text;
        }


    }

    /**
     * A simple class which holds some information-fields
     * about some Guys.
     */
    private class Guy{
        private final String name;
        private final int age;

        public Guy(String name, int age){
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }
    }
}

我完全评论了代码,如果您有任何问题,请不要犹豫,问他们。

答案 1 :(得分:8)

最简单的解决方案

在SO上搜索不同的解决方案后,我发现以下是使用自定义Spinner填充Objects的最简单,最干净的解决方案。这是完整的实施:

Location.java

public class Location{
    public int id;
    public String location;

    @Override
    public String toString() {
        return this.location;            // What to display in the Spinner list.
    }
}    

RES /布局/ spinner.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="14sp"
    android:textColor="#FFFFFF"
    android:spinnerMode="dialog" />

RES /布局/ your_activity_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Spinner
        android:id="@+id/location" />

</LinearLayout>

在您的活动中

// In this case, it's a List of Locations, but it can be a List of anything.
List<Location> locations = Location.all();                  

ArrayAdapter locationAdapter = new ArrayAdapter(this, R.layout.spinner, locations);

Spinner locationSpinner = (Spinner) findViewById(R.id.location);
locationSpinner.setAdapter(locationAdapter);



// And to get the actual Location object that was selected, you can do this.
Location location = (Location) ( (Spinner) findViewById(R.id.location) ).getSelectedItem();

答案 2 :(得分:6)

感谢上面的Lukas回答(下面?)我能够开始这个,但我的问题是他的getDropDownView的实现使得下拉项只是一个纯文本 - 所以没有填充,没有使用android.R.layout.simple_spinner_dropdown_item时可以获得漂亮的绿色单选按钮。

如上所述,除了getDropDownView方法之外:

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) 
{
  if (convertView == null)
  {
    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = vi.inflate(android.R.layout.simple_spinner_dropdown_item, null);
  }

  TextView textView = (TextView) convertView.findViewById(android.R.id.text1);
  textView.setText(items.get(position).getName());

  return convertView;
}

答案 3 :(得分:3)

好吧,我不会对更多细节感到困惑。

只需创建 ArrayList ,然后绑定您的值。

ArrayList tExp = new ArrayList();
for(int i=1;i<=50;i++)
{
    tExp.add(i);
}

假设您的布局上已经有一个微调器控件,请说id为spinner1。在下面添加此代码。

Spinner sp = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adp1=new ArrayAdapter<String>this,android.R.layout.simple_list_item_1,tExp);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adp1);

以上所有代码都在onCreate函数下。

答案 4 :(得分:2)

感谢Lukas,你帮了我很多忙。 我想改善你的答案。 如果您以后想要访问所选项目,可以使用:

Spinner spn   = (Spinner) this.findViewById(R.id.spinner);
Guy     oGuy  = (Guy)     spn.getSelectedItem();

所以你不必在初始化时使用setOnItemSelectedListener():)