2

I have next code in my DialogFragment:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Log.i(getClass().getName(), "onCreateDialog");
    final FileSystemAdapter adapter = getAdapter();
    adapter.showFS(null);

    AlertDialog b = new AlertDialog.Builder(getActivity())
            .setTitle(title)
            .setCancelable(false)
            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //some actions
                }
            })
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dismiss();
                }
            })
            .setAdapter(adapter, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    adapter.showFS(adapter.getItem(i));
                }
            })
            .create();
    return b;
}

After clicking on element of list, last onClick method is invoking and then dialog is closing.


How to prevent this behavior and stay dialog opened until dismiss method called?

1 Answer 1

7

You can make a new ListView and set it as a custom view in AlertDialog.Builder and put your OnClickListener code into OnItemClickListener in listView. Try something like this:

ListView listView = new ListView(this);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new ListView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> listView, View itemView, int position, long itemId) {
         adapter.showFS(adapter.getItem(position));
    }
});

AlertDialog b = new AlertDialog.Builder(getActivity())
        .setTitle(title)
        .setCancelable(false)
        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //some actions
            }
        })
        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dismiss();
            }
        })
        .setView(listView)
        .create();
return b;
1
  • Thank you! I did it 10 minutes before and it works. That's weird but so )
    – Divers
    Jun 23, 2013 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.