简体   繁体   中英

android: How to populate a spinner with a string[] which is a list of installed packages?

 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    final List pkgAppsList = this.getPackageManager().queryIntentActivities( mainIntent, 0);
    final String[] apps = (String[]) pkgAppsList.toArray();
    Spinner appSpinner = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> appAdapter = new ArrayAdapter(this, apps, android.R.layout.simple_spinner_item);
    appAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    appSpinner.setAdapter(cloudAdapter);

The previous code is throwing out errors for me in eclipse. I understand how to get the list of installed apps, and I understand how to populate a spinner using the createFromResource method. However I've never attempted to do so in this manner? Anyone able to direct me in the right direction?

Eventough it is late, you should use this constructor of ArrayAdapter instead :

ArrayAdapter<String> appAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, apps);
appAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
appSpinner.setAdapter(appAdapter);

Create a file named arrays.xml inside values folder.

Inside that give:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="array_name">
        <item>value1</item>
        <item>value2</item>
    </string-array>
</resources>

Then inside your spinner,give:

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.array_name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);

Hope this may work for you.

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