0

i have two buttons put in line inside layout. i d' like them to have the same width. but width of every button have to be equal the widest of them. now i use ViewTreeObserver.

    class LayoutListener implements ViewTreeObserver.OnGlobalLayoutListener{
    private Button btn1, btn2;

    public LayoutListener(Button b1, Button b2){
        btn1 = b1; btn2 = b2;
    }
    @Override
    public void onGlobalLayout() {
        int w1 = btn1.getWidth();
        int w2 = btn2.getWidth();
        if (w1 < w2)
            btn1.setWidth(w2);
        else
            btn2.setWidth(w1);
    }
}

but it's not good decision becase elements are redrawn after they was shown to the user and it looks terrible. and question as you can guess, how can i reach needed behavior? is there way of markup manipulating or i should implement special code? it's desirable to avoid creating custom layout that could be used as a container for buttons.

DotNetter
  • 426
  • 2
  • 6
  • 19

2 Answers2

0

Could you compare the button width's in the onCreate() method of your activity and set them then, or do you need to change their size at a different time?

EDIT:

After you inflate your view you can create two Button variables and use (Button)yourViewName.findViewById(R.id.buttonid); to bind them. You can then use getWidth() and setWidth() to compare and modify them as you need.

Nate
  • 401
  • 2
  • 7
  • i create view as: view = inflator.inflate(R.layout.list_view_item, null) and cannot catch oncreate method. And besides that, if i'm not mistaken (i 'm new in android developement), getting calculated sizes is possible only in onMesure method, is not it. – DotNetter Jun 11 '12 at 23:23
  • Are the buttons defined inside of an xml file? – Nate Jun 11 '12 at 23:48
  • sorry for late answer. i was needed to set aside my android project for a while. I've tried as you recommended: see my answer in this topic – DotNetter Jul 10 '12 at 20:48
0

if i call getWidth derectly after inflatation it's always return 0. To prevent it before get size i should init measure process by using measure function. This is my code (but i' m not sure it's the best and the fastest way)) ):

....
view = inflator.inflate(R.layout.send_command_item, null);
btnOff = (Button)view.findViewById(R.id.btnOff);
btnOn = (Button)view.findViewById(R.id.btnOn);
set_w(btnOff, btnOn);
.....

public void set_w(Button btn1, Button btn2) {
    btn1.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    btn2.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    int w1 = btn1.getMeasuredWidth();
    int w2 = btn2.getMeasuredWidth();
    if (w1 < w2)
        btn1.setWidth(w2);
    else
        btn2.setWidth(w1);
}
DotNetter
  • 426
  • 2
  • 6
  • 19