java – Spinner subitem

I want to populate the spinner with projects that contain main text and sub text, as Android studio shows when building views on the designer tab

So far, I can only fill it in with the text

I do it through code Use simpleadapter

I tried the following but failed. It only gave me the same result (only the text):

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);

Solution

I encountered the same problem and used OP's code as the basis for creating this solution:

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);

You can also add Android R.layout. simple_ spinner_ Item and / or Android R.layout. simple_ list_ item_ 2 replace with your own custom view (usually in the layout folder)

This is a better solution than phonegap!: d

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>