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

jan*_*han 14 data-binding android arraylist spinner android-arrayadapter

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

private ArrayList<Locations> Artist_Result = new ArrayList<Location>();
Run Code Online (Sandbox Code Playgroud)

此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);
Run Code Online (Sandbox Code Playgroud)

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

Luk*_*uth 38

ArrayAdapter尝试显示您的Location-objects作为字符串(这会导致十六进制值),通过调用Object.toString()-方法.它的默认实现返回:

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

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

@Override
public String toString(){
  return "Something meaningful here...";
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是,扩展BaseAdapter 实现SpinnerAdapter来创建自己的Adapter,它知道你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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Jos*_*ter 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.
    }
}    
Run Code Online (Sandbox Code Playgroud)

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" />
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

在你的活动中

// 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();
Run Code Online (Sandbox Code Playgroud)


Mic*_*rne 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;
}