【问题标题】:android Spinner: get the item selected before onItemSected was calledandroid Spinner:在调用onItemSected之前获取选中的项目
【发布时间】:2013-01-07 12:13:49
【问题描述】:

我有一个在视图中动态创建的微调器列表。单击微调器时,它会返回当前选定的项目。有什么方法可以让我获得在此选择之前存在的项目?

除了 onItemSelected() 之外还有其他可能的事件吗?

【问题讨论】:

  • 我认为您将能够从您设置的值中知道微调器可能具有的默认值。

标签: android android-spinner


【解决方案1】:

请看这段代码:

Spinner sp= (Spinner) findViewById(R.id.type_spinner);
sp.setOnItemSelectedListener(this);

这是您选择的微调器值的方法:

如果您没有任何选择值,则默认选择第一个值

public void onItemSelected(AdapterView<?> parent, View view, int position,
        long arg3) {

    String main = (int) parent.getSelectedItemId();

    Log.e("Spinner Value",main);

}

【讨论】:

  • 这给了我和我一样的输出:String main=position
【解决方案2】:

错误答案,问题误解

当你的onItemSelected() 被调用时,你会得到一个position 参数。您可以使用position - 1 知道元素在所选元素之前的位置。如果您有一个对应元素数组,它们的微调器元素位置相似,那么corresponding_spinner_array[position-1] 应该会为您提供所需的元素。

问题重构后

为什么不只记住单个变量中的每个选择?

更新示例:

    String[] items = {"a","b","c"};
    String selectedItem;
    /*get your spinner element from your XML layout*/
    /*or if you already have access to it, no need for this*/
    Spinner spin = (Spinner) findViewById(R.id.spinner);
    spin.setOnItemSelectedListener(this);

    ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
    android.R.layout.simple_spinner_item, items);

    spin.setAdapter(aa);

    public void onItemSelected(AdapterView<?> parent, View v, int position,
     long id) {
          selectedItem = items[position];     
      }

【讨论】:

  • 这不是我要找的东西,我想要之前在微调器中的项目,当我选择一个新项目时它被更改了
  • 你为什么不记住每一个选择?请重新定义您的问题,以明确您想要什么。
【解决方案3】:

可能不会,你必须保持自己的价值。 AdapterView 确实有一个mOldSelectedPosition 字段,但它不可访问。

【讨论】:

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