我想在Spinner中填充包含主文本和子文本的项目,就像
Android Studio在“Designer”选项卡上构建视图时所显示的那样.
到目前为止,我只能用正文填写它.
我是通过代码来做的.使用SimpleAdapter.
我尝试了以下但没有成功,它只给了我相同的结果(只有正文):
Spinner spinner = (Spinner) findViewById(R.id.mySpinner); List<Map<String,String>> itens = new ArrayList<>(); Map<String,String> item = new HashMap<>(2); item.put("text","MAIN TEXT"); item.put("subText","SUB TEXT"); itens.add(item); SimpleAdapter adapter = new SimpleAdapter(spinner.getContext(),itens,android.R.layout.simple_spinner_dropdown_item,new String[]{"text","subText"},new int[]{android.R.id.text1,android.R.id.text2} ); // i am not sure what this does adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter);
解决方法
我遇到了同样的问题,并使用OP的代码作为创建此解决方案的基础:
final Spinner spinner = (Spinner)fragmentView.findViewById(R.id.spinner); List<Map<String,String>> items = new ArrayList<Map<String,String>>(); Map<String,String> item0 = new HashMap<String,String>(2); item0.put("text","Browse aisles..."); item0.put("subText","(Upgrade required)"); items.add(item0); Map<String,String> item1 = new HashMap<String,String>(2); item1.put("text","Option 1"); item1.put("subText","(sub text 1)"); items.add(item1); Map<String,String> item2 = new HashMap<String,String>(2); item2.put("text","Option 2"); item2.put("subText","(sub text 2)"); items.add(item2); SimpleAdapter adapter = new SimpleAdapter(getActivity(),items,android.R.layout.simple_spinner_item,// This is the layout that will be used for the standard/static part of the spinner. (You can use android.R.layout.simple_list_item_2 if you want the subText to also be shown here.) new String[] {"text",new int[] {android.R.id.text1,android.R.id.text2} ); // This sets the layout that will be used when the dropdown views are shown. I'm using android.R.layout.simple_list_item_2 so the subtext will also be shown. adapter.setDropDownViewResource(android.R.layout.simple_list_item_2); spinner.setAdapter(adapter);
您还可以将android.R.layout.simple_spinner_item和/或android.R.layout.simple_list_item_2替换为您自己的自定义视图(通常位于布局文件夹中).
这是一个比PhoneGap更好的解决方案! :d