Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AlertDialog style buttons for an Activity

Tags:

java

android

I have an activity with a Save and Cancel button at the bottom.

In AlertDialog, the buttons are displayed inside a styled container view of some sort.

How could I give the buttons in my Activity that same appearance? Specifically, how could I apply the style of the button container view in the AlertDialog to say a LinearLayout in my Activity containing the buttons?

Thanks

like image 267
CL22 Avatar asked Apr 20 '11 19:04

CL22


2 Answers

There are solutions given elsewhere that work. In short, you can simply use style attributes in your xml to achieve this. For instance, style="?android:attr/buttonBarStyle" and style="?android:attr/buttonBarButtonStyle" will do the job (for API 11+). Here is an example of two buttons horizontally put together.

<LinearLayout
    style="?android:attr/buttonBarStyle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:measureWithLargestChild="true"
    android:orientation="horizontal"
    android:paddingTop="0dip" >

    <Button
        style="?android:attr/buttonBarButtonStyle"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text= "Ok" />

    <Button
        style="?android:attr/buttonBarButtonStyle"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Cancel" />
</LinearLayout>

The only thing that remains, is that there is a horizontal line right above the buttons in an alertDialog, which the above code will not create. If you want to have that horizontal line, it should be added manually in the xml, above the LinearLayout. This will give you the horizontal line:

<View
    android:layout_width="fill_parent"
    android:layout_height="1dp"
    android:layout_marginBottom="0dp"
    android:background="?android:attr/dividerVertical" /> 
like image 140
hadi Avatar answered Sep 21 '22 13:09

hadi


I do some thing like this:

LinearLayout dialogLayout = (LinearLayout) ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dialog_addeditrecord, null);

I then use the dialogLayout to call findViewById() to pull in the buttons and other views and setup OnClickListeners and such...

then to show the dialog:

builder = new AlertDialog.Builder(this);

builder.setView(dialogLayout);

builder.create().show();
like image 44
Maximus Avatar answered Sep 24 '22 13:09

Maximus