1

I want to make a button square with the width the same as the heigth.
I try bt.setWidth(bt.getHeight()) but it doesn't work.
If I hardcode the width (bt.setWidth(90)) it works but I don't know the height so I can hardcoded it.

Here is some code. When I click on a button, it opens a dialog and this dialog must contain the square button.

public class MyClass extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myLayout);
    }

    public void doClick(View view) {
        final Dialog dialog = new Dialog(view.getContext());
        dialog.setContentView(R.layout.dialogLayout);
        dialog.setTitle("Title");

        Button bt = (Button) dialog.findViewById(R.id.myButton);
        bt.setWidth(bt.getHeight());
        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ...
            }
        });

        dialog.show();
    }   
}

How could I do it?

4
  • 1
    Please show the code. Are you doing this in onCreate()?
    – Simon
    Commented Sep 23, 2012 at 8:37
  • I just edit my question.
    – Snote
    Commented Sep 23, 2012 at 8:46
  • Is that a copy/paste? Is this line how it looks in your code ------ bt.setWidth(bt.getHeight() I would expect a closing bracket and semicolon at the end of that line.
    – Simon
    Commented Sep 23, 2012 at 8:47
  • I remove something and I delete ); I add it back. Of course in my code the closing bracket and semicolon are in.
    – Snote
    Commented Sep 23, 2012 at 8:50

1 Answer 1

2

The direct answer is that until the dialog is displayed, it has not measured it's layout and the button height will be zero. You could extend the Dialog class and override the onMeasure() method or attach a global layout listener to the layout and set the button size in onLayoutComplete().

However, your approach might be wrong. Why can't you do this in the dialog's layout XML?

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