如何从onItemSelected方法中获取选定的微调器项的值



我试图从一个旋转器中获取所选值以存储它并稍后使用它。我已经尝试了两种不同的方法:

  1. 返回空值
  2. 只打印列表的第一个值,当我选择另一个值时它不打印任何东西。

方式1

public class genera_debate extends Fragment implements AdapterView.OnItemSelectedListener {
public String text;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_genera_debate,container,false);
list_of_interest =view.findViewById(R.id.subject_of_interest);
String [] subject = {"Tema de interés","Política","Deporte","Animales","Videojuegos","Economía","Medicina","Cultura","Ciencia","Tecnología","Música","Otros"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, subject);
list_of_interest.setAdapter(adapter);
list_of_interest.setOnItemSelectedListener(this);
Toast.makeText(getActivity(), "value is"+text, Toast.LENGTH_SHORT).show();
return view;}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
text=list_of_interest.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
2

方式

public class genera_debate extends Fragment implements AdapterView.OnItemSelectedListener {
public String text;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_genera_debate,container,false);
list_of_interest =view.findViewById(R.id.subject_of_interest);
String [] subject = {"Tema de interés","Política","Deporte","Animales","Videojuegos","Economía","Medicina","Cultura","Ciencia","Tecnología","Música","Otros"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, subject);
list_of_interest.setAdapter(adapter);
list_of_interest.setOnItemSelectedListener(this);
text=list_of_interest.getSelectedItem().toString();
Toast.makeText(getActivity(), "value is"+text, Toast.LENGTH_SHORT).show();
return view;}
}

我希望你能帮助我,regards

在onItemSelectedListener方法中定义Toast

这里的问题是,当你的视图被创建时,吐司被调用,因为它在onCreate方法中,一旦你的活动开始就会被调用,因此你的吐司只在你的视图被创建时被调用,这意味着只有一次。

如果你想让它在每次选择新值时出现,你需要在onItemSelectedListener中定义它,因为这个方法将在每次选择下拉列表中的新值时被调用。

希望这对你有帮助。

相关内容

  • 没有找到相关文章

最新更新