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

跟風遠走 提交于 2019-12-01 21:49:58

问题


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.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/15406535/accountmanager-how-to-let-the-user-select-an-account-using-a-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!