Alex Rivera | Logout

Correct text color/appearance in AlertDialog

Asked 2012-12-25T18:20:29.097
8

I am struggling around with this problem for quite a long time. I searched for solutions and there were actually some suggestions for related problems, but nothing really worked correctly for me. So let's say I want to create an AlertDialog with a (long) message, a checkbox and two buttons.

// create dialog
AlertDialog.Builder dlg = new AlertDialog.Builder(this);
dlg.setTitle(R.string.dlg_title);
dlg.setMessage(R.string.dlg_msg);

// add checkbox
final CheckBox checkbox = new CheckBox(this);
dlg.setView(checkbox);

// add buttons
dlg.setPositiveButton(...);
dlg.setNegativeButton(...);

// show dialog
dlg.show();

This won't work, because if the dialog message becomes too long, the checkbox will not be completely shown. Additionally, it is going to be completely hidden in landscape mode.

Next try would be to lookup the original dialog layout file (for me it is located under android-sdk-linux_86/platforms/android-17/data/res/layout/alert_dialog.xml) and attempt to copy the relevant part to create our own "clone" of the inner dialog layout, just like this:

dialog_checkbox.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:overScrollMode="ifContentScrolls"
        android:paddingBottom="12dip"
        android:paddingLeft="14dip"
        android:paddingRight="10dip"
        android:paddingTop="2dip" >

        <TextView
            android:id="@+id/message"
            style="?android:at
Edit
Report

1 Answer

19

I had the same problem and solved it by creating a ContextThemeWrapper for my desired Dialog Theme and used this when creating the AlertDialog Builder and when inflating the View to attach:

ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DialogBaseTheme);
AlertDialog.Builder builder = new AlertDialog.Builder(wrapper);
View view = LayoutInflater.from(wrapper).inflate(R.layout.create_warning, null); 
builder.setView(view);

The style R.style.DialogBaseTheme is defined in "/values/styles.xml" for Gingerbread and below as:

<style name="DialogBaseTheme" parent="android:Theme.Dialog"/>

Then it is also defined in "/values-v11/styles.xml" for Honeycomb and upward to use the Holo theme as:

<style name="DialogBaseTheme" parent="android:Theme.Holo.Light.Dialog" />

So on Gingerbread my custom View's TextViews are automatically coloured white and Honeycomb+ they are automatically coloured black for Holo Light.

answered 2013-07-02T19:05:21.223

Your Answer