从OnItemSelectedListener调用值

时间:2019-03-07 07:57:58

标签: android android-spinner onitemselectedlistener

我有一个来自Spinner中所选项目的值,该值使用spinner.setOnItemSelectedListener()传递给String变量'selectedSpinner'。我正在尝试在方法之外访问'selectedSpinner'

我尝试将'selectedSpinner'分配给另一个字符串'selectedCategory',但是在spinner.setOnItemSelectedListener()方法之外,'selectedSpinner'无法解决。在方法之外访问'selectedSpinner'应该怎么做?谢谢

private void recordDialog() {

    ...
    //get category
    final Spinner spinner = subView.findViewById(R.id.spinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selectedSpinner = parent.getItemAtPosition(position).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
    final String selectedCategory = selectedSpinner;
    ...
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

1 个答案:

答案 0 :(得分:0)

您需要在selectedSpinner函数外部声明recordDialog(或将其设置为全局)

String selectedSpinner;
          ...
private void recordDialog() {
          ...... 
     @Override
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
         selectedSpinner = parent.getItemAtPosition(position).toString();
      }
}

之后,您可以将selectedSpinner分配给selectedCategory