简体   繁体   中英

AccountManager: How to let the user select an Account using a Dialog

In the AccountManager tutorial Remembering Your User , it's recommended:

If there's more than one Account in the array, you should present a dialog asking the user to select one.

What's the best way to do this? I have a solution in mind, but if there are other good examples from the community, it seems like this is the kind of boilerplate code that could be shared and easily re-used by others.

From Android 4.0 (API level 14) onwards, launching an activity with an intent shown below, shows account chooser.

Intent intent = AccountManager.newChooseAccountIntent(null, null,
        new String[] { acc_type }, true, null, null,
        null, null);
startActivityForResult(intent, CHOOSE_ACCOUNT);

For devices older than 4.0,
use https://github.com/frakbot/Android-AccountChooser

I use this code. It show an dialog, so enduser can choose one of the google account.

ArrayList<String> gUsernameList = new ArrayList<String>();
AccountManager accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");

gUsernameList.clear();
//loop
for (Account account : accounts) {
    gUsernameList.add(account.name);
}

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose you gmail-account");

ListView lv = new ListView(this);

ArrayAdapter<String> adapter = new ArrayAdapter<String> 
(this,android.R.layout.simple_list_item_1, android.R.id.text1, 
gUsernameList);

lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {    

public void onItemClick(AdapterView<?> parent,View view,int position,long 
id) 
{
    Log.d("You-select-gmail-account", gUsernameList.get(position)) );
}
});

builder.setView(lv);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        dialog.dismiss();
    }
});

final Dialog dialog = builder.create();
dialog.show();

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