Permanently adding an item to an existing alertdialog?

前端 未结 2 1285
死守一世寂寞
死守一世寂寞 2021-01-23 08:54

My goal is to permanently add an item to an existing AlertDialog.

The XML array for the AlertDialog is:


    

        
相关标签:
2条回答
  • 2021-01-23 09:12

    I'm nor sure if I understood your question... but I'll try to answer. First, you can add dinamically new options to the alertDialog after you inflate them. What you can't do is add new lines to the xml from where you inflate them.

    Having said that, you need to store the new servers somewhere when the activity finish, so you can recover them later. For this you have several options, and I'll start with the one I believe is the simplest:

    Store the servers in a shared preferences file:

    Saving example

        Editor editor = getSharedPreferences("FileName", MODE_PRIVATE).edit();
        editor.clear();
        editor.putString("server1", "serverName1");
        editor.putString("server2", "serverName2");
        editor.commit();
    

    Reading example:

        SharedPreferences preferences = getSharedPreferences("FileName", MODE_PRIVATE);
        preferences.getString("server1", "defaultValue");
        preferences.getString("server2", "defaultValue");
    

    You can also use a database to store the values. This would be better if you expect to have a list with hundreds of servers, as the performance of previous solution would be pour in this case.

    Finally, you could store the information in a file, but that would require more code and I don't see any true benefit of it.

    If I didn't answer you question, just let me know. Good luck.

    0 讨论(0)
  • 2021-01-23 09:35

    You can leave the defaults in the xml file but you'll need to store the custom servers in a database. Then you can pull from both sources into a single array and put that in the dialog.

    final CharSequence[] items = {"Red", "Green", "Blue"};
    
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Pick a color");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog alert = builder.create();
    
    0 讨论(0)
提交回复
热议问题