简体   繁体   中英

Best way to implement ArrayList in Android Studio

i have 30 items in ArrayList and its implement in Spinner, i placed it in java file like this

ArrayList<String> listProblemSolving = new ArrayList<>();
    listProblemSolving.add("List1");
    listProblemSolving.add("List2");
    listProblemSolving.add("List3");
    listProblemSolving.add("List4");
    listProblemSolving.add("List5");
    listProblemSolving.add("List6");
    listProblemSolving.add("List7");
    ...
    ArrayAdapter<String> adapterProblemSolving = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, listProblemSolving);

and i implement in spinner like this

sp.setAdapter(adapterProblemSolving);

The question is, can i store the list item in strings file? And is there any simply way if i want to give different action to item list, for example i try this one

    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             if (position == 1)
                // do something

             if (position == 2)
                // do something

             ...
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Thank you and sorry i you found this as dupplicate question.

You can create a string-array in your strings.xml file and use that in your Adapter.

Here is the example:

<resources>
   <string-array name="numbers">
      <item>1</item>
      <item>2</item>
      <item>3</item>
      <item>4</item>
   </string-array>
</resources>

In your activity, you can use it like the following code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String[] numbers = getResources().getStringArray(R.array.numbers);
    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
      android.R.layout.simple_spinner_dropdown_item, numbers);
    spinner.setAdapter(adapter);
}

Well, if your entries are simple strings then you can try this

In your strings.xml

<string-array name="data_array">
   <item>value 1</item>
   <item>value 2</item> 
   <item>value 3</item>
 </string-array>

In your xml layout for spinner

<Spinner  
 ... 
 ...
android:entries="@array/data_array" />

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