这个Spinner片段是否正确?选择项目时如何触发操作?

时间:2015-09-19 20:17:30

标签: java android fragment spinner

我在我的" Fragment_first"中实施了Spinner,但我认为这是不正确的。应用程序正在运行,但是有更好的方法吗?如何添加功能,如果我选择Item 1,它会向我显示带有文字的祝酒词" ..."?



@Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_first, container, false);

            final List<String> list=new ArrayList<String>();
            list.add("Item 1");
            list.add("Item 2");
            list.add("Item 3");

            Spinner s = (Spinner) rootView.findViewById(R.id.spinner);
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, list);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s.setAdapter(dataAdapter);

            return rootView;
        }
    }
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您走在正确的道路上,请阅读微调器的文档:

http://developer.android.com/guide/topics/ui/controls/spinner.html

以下是您要实现的目标示例:

s.setOnItemSelectedListener(new OnItemSelectedListener() 
{
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) 
    {
        //Access your list object via list.get(position)
        Toast.makeText(getActivity(), "item = " + list.get(position), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) 
    {
        //nothing selected
        Toast.makeText(getActivity(), "nothing selected", Toast.LENGTH_LONG).show();
    }
});