Search code examples
androiddialogandroid-preferences

Are there built in dialogs for input for text, lists, etc... like builtin preference screens?


In a preference fragment when you click on an item that is an EditTextPreference or ListPreference or others... it automatically opens a dialog box allowing input or selection depending on what you have it setup as.

If you are NOT using a PrefFrag.... but writing your own input screens, are there any built-in dialogs that can be called to do that or do we have to create our own from scratch?


Solution

  • You have to build them yourself, though most of the code can be easily copied from this article, with slight changes: http://developer.android.com/guide/topics/ui/dialogs.html

    Choosing an item from a list is included there. For a text field, you would need to do something slightly different. Here is an example. Use it in an Activity:

        //First, set these variable to what you want
        String title = "ENTER A TITLE HERE";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
    
        // Set up the input
        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        builder.setView(input);
    
        // Set up the buttons
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String text = input.getText().toString();
                //text is the String the user inputted, use it for what you need here
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //This means the user hit Cancel instead of OK
            }
        });
    
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();