Diana Diana - 3 months ago 33
Android Question

Android - close popUp window

I have a listView inside a popUp window and I want that when the user clicks on an item in the listview, the popUp window will automatically close. Any idea how I can do that?

public void popUp(){
final LayoutInflater layoutInflater = LayoutInflater.from(Record.this);

final View promptView = layoutInflater.inflate(R.layout.input_language, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Record.this);
alertDialogBuilder.setView(promptView);

String[] languages = {"Arabic","Bulgarian","Catalan"};

ListView list = (ListView) promptView.findViewById(R.id.inputlang);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, languages);
list.setAdapter(adapter);

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {

String from_language = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), from_language, Toast.LENGTH_LONG).show();

// CLOSE POPUP WINDOW
}
});

// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});

// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}

Answer

You can do this by changing the order of initialization of the dialog:

public void popUp(){
    final ListView promptView = new ListView(this);
    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setView(promptView);
    // setup a dialog window
    alertDialogBuilder.setCancelable(false)
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

    // create an alert dialog
    final AlertDialog alert = alertDialogBuilder.create();

    String[] languages = {"Arabic","Bulgarian","Catalan"};

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, languages);
    promptView.setAdapter(adapter);

    promptView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            String from_language = ((TextView)view).getText().toString();
            Toast.makeText(getBaseContext(), from_language, Toast.LENGTH_LONG).show();

            // CLOSE POPUP WINDOW
            alert.dismiss();
        }
    });

    alert.show();
}
Comments