Search code examples
androidscrollviewandroid-alertdialogandroid-2.3-gingerbread

Custom AlertDialog ScrollView, too big in 2.3 missing ok button


I have to show a help info, instructions of how to use the program, i've chosen the AlertDialog using a custom XML with an ScrollView. I tested in tablet, xperia neo and 2 virtual devices. In 3 of them goes good, but in the 2.3 with small screen,the dialog is too big and has a bug in the visualization that makes it hard to close. Any idea why? Here is my code: XML for the ScrollView:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" 
    android:textSize="10sp">
    </TextView>
</ScrollView>`

And for my code for calling it:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(R.string.msg_help)
           .setCancelable(false)
           .setView(LayoutInflater.from(this).inflate(R.layout.dialog_scrollable,null))
           .setTitle(R.string.help_title)
           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    //do things
               }
           });
    AlertDialog alert = builder.create();
    alert.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    alert.show();

Here is how it looks: http://postimg.org/image/wvg61x0qv/


Solution

  • An AlertDialog makes its content scrollable automatically if it wouldn't fit on the screen. Instead of inflating your custom XML layout, simply just set the text to the dialog with builder.setText()builder.setMessage().

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(R.string.msg_help)
           .setCancelable(false)
           .setTitle(R.string.help_title)
           .setMessage(R.string.help)
           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    //do things
               }
           });
    AlertDialog alert = builder.create();
    alert.show();
    

    Notice that I also removed the line with alert.getWindow().setLayout() because I think it's useless.