对话框中的 OnItemSelectedListener

OnItemSelectedListener in Dialog

我在对话框中有一个微调器,我试图从微调器中的所选项目中获取值并将其传递给一个字符串变量。我找到的方法是 spinner.setOnItemSelectedListener()。

但是,此方法需要在对话框外设置另一种方法。下面附上代码。

这是对话框的代码

private void recordDialog() {
    LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
    View subView = inflater.inflate(R.layout.record, null);

    //get current date
    Calendar calendar = Calendar.getInstance();
    String pattern = "dd-MMM-yy";
    DateFormat dateFormat = new SimpleDateFormat(pattern);
    final String currentDate = dateFormat.format(calendar.getTime());

    //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(this);
    ...
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

以及对话框外的部分

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

是否可以在对话框中完成所有操作?

好吧,您可以在 recordDialog 函数中实现 onItemSelectedListener

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
         // Do your stuff here    
      }

      public void onNothingSelected(AdapterView<?> parent) {
         // Do your stuff here  
      }
  });
}