简体   繁体   中英

Android populate Spinner with 2 ArrayList

How can I populate a spinner with 2 ArrayList? For example: I have 2 arrayList

<string-array name="month">
<item>Gen</item>
<item>Feb</item>
<item>Mar</item>
</string-array>

<string-array name="monthN">
<item>0</item>
<item>01</item>
<item>02</item>
</string-array>

In the spinner I would like to see the lists in this way:

0 Gen 01 Feb 02 Mar

now I have a simple Adapter

ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(this, R.array.month,
        android.R.layout.simple_spinner_item);
            arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    monthSelector.setAdapter(arrayAdapter);

Iterate over your String arrays and concatenate the strings together. That would look something like this:

ArrayList<String> concatenated = new ArrayList<>();
String[] months = getResources().getStringArray(R.string.month);
String[] numbers = getResources().getStringArray(R.string.monthN);
for(int i = 0; i < months.length; i++) {
    concatenated.add(numbers[i] + " " + months[i]);
}

Now each element of concatenated will look like NUMBER NAME .

If you want the Month to appear in the spinner, and the selected value to be the number, try this:

 private void method name{
 ArrayList<dateStruct> datesArray = new ArrayList(dateStruct>();
 dateStruct = new dateStruct();
 String[] months = getResources().getStringArray(R.string.month);
 String[] numbers = getResources().getStringArray(R.string.monthN);
 // Build dates list and add to datesArray
 for(int i = 0; i < months.length; i++) {
    dateStruct.dateNumber = numbers[i];
    dateStruct.dateName = months[i];
    datesArray.add().dateStruct();
}

// bind to Spinner control
ArrayAdapter<dateStruct> arrayAdapter = new ArrayAdapter< (MainActivity.this, R.layout.support_simple_spinner_dropdown_item, datesArray);
taskListDropdown_control.setAdapter(arrayAdapter);
}

 public class dateStruct
   {
      public String dateNumber;
      public String dataName;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM