0

I am trying to create Alertdialog and add 3 togglebuttons with images to it programmatically.

I tried starting with one togglebutton and for some reason the alert dialog is really small (just around the image) and the button itself looks weird(image bigger than button)..

Here is my code, do spot anything wrong?

LinearLayout ll = new LinearLayout(mActivity);
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    ToggleButton tb;
    for(int i=0;i<cards.size();i++){
        Card card = cards.get(i);
        tb = new ToggleButton(mActivity);
        tb.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        tb.setButtonDrawable(card.getDrawable(mActivity));
        ll.addView(tb);
    }


    AlertDialog.Builder builder;
    AlertDialog alertDialog;
    builder = new AlertDialog.Builder(mActivity);
    builder.setView(ll);
    alertDialog = builder.create();
    alertDialog.show();
4

1 回答 1

1

I found out that sometimes with Dialog or AlertDialog, even though you set FILL_PARENT to the root layout, the dialog won't fill up the screen. It will behave actually like WRAP_CONTENT.

So I ended up setting a fixed dialog width most of the time.

Try setting your root linearlayout to a fixed width:

ll.setLayoutParams(new LayoutParams(280 * scalingFactor, LayoutParams.FILL_PARENT));

Where scalingFactor is the screen density (1 for mdpi, 1.5 for hdpi, etc).

However, I suggest using an XML layout for your alert dialog. It's easier to see what it looks like in the Designer as opposed of doing it in code. e.g. let's call this layout file my_toggle_button.xml:

<LinearLayout android:layout_width="280dp" android:layout_height="wrap_content"
    android:orientation="vertical">
   <ToggleButton android:background="@drawable/customToggleButton" />
   <ToggleButton android:background="@drawable/customToggleButton" />
   <ToggleButton android:background="@drawable/customToggleButton" />
</LinearLayout>

Then define how you want the ToggleButton to look in a customToggleButton.xml drawable

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_checked="false" android:drawable="@drawable/toggleButtonUnchecked" />
   <item android:state_checked="true" android:drawable="@drawable/toggleButtonChecked" />
</selector>

You will need to supply two PNGs toggleButtonUnchecked.png and toggleButtonChecked.png.

In your code, instead of building the controls, just inflate R.layout.my_toggle_button into a view and call the AlertDialog's setView on it.

于 2012-07-16T04:45:38.490 回答