【问题标题】:Android Spinner databind using array list使用数组列表的 Android Spinner 数据绑定
【发布时间】:2011-09-27 13:56:51
【问题描述】:

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

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);

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

【问题讨论】:

  • 作为一个简单的快速而肮脏的解决方案,您可以简单地在Locations 中实现toString()

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


【解决方案1】:

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

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

要使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;
        }
    }
}

我对代码进行了完整的注释,如果您有任何问题,请不要犹豫。

【讨论】:

  • 我是 Android 应用程序开发的新手。所以,如果你能给我一些你给定解决方案的示例代码,我很感激。谢谢 Lukas Knuth。
  • 非常感谢 Lukas Knuth,您的示例运行良好。谢谢:)))))
  • “getViewTypeCount”方法处理不正确。对于这种类型的适配器,它应该返回 1。适配器尝试回收视图,如果它们知道有超过 1 个视图,它可能不会以最佳方式回收它们。阅读该方法的 JavaDoc。
  • 这真的很好,但唯一让我烦恼的是@Override public int getItemViewType(int position) { return android.R.layout.simple_spinner_dropdown_item; } 不起作用。
  • 如何设置按年龄项选择
【解决方案2】:

最简单的解决方案

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

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/layout/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/layout/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();

【讨论】:

    【解决方案3】:

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

    如上,除了getDropDownView 方法是:

    @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { 如果(转换视图 == 空) { 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()); 返回转换视图; }

    【讨论】:

    • 谢谢,我找这个太久了。
    【解决方案4】:

    好吧,我不会混淆更多细节。

    只需创建您的 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 函数下。

    【讨论】:

      【解决方案5】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-07
        • 1970-01-01
        相关资源
        最近更新 更多