position view in relativelayout runtime

前端 未结 2 878
余生分开走
余生分开走 2021-01-27 01:31

i want to add a view to a relativelayout. this view must be added to a specified position.

i have this:

    int x = ...;
    int y = ...;
    button.setO         


        
相关标签:
2条回答
  • 2021-01-27 01:52

    You might want to try setting the position of your button before you add it to the parent view. So just swap these two lines:

    relativelayout.addView(button);
    button.layout(x, y, x + button.getWidth(), y + button.getHeight());
    

    to be this:

    button.layout(x, y, x + button.getWidth(), y + button.getHeight());
    relativelayout.addView(button);
    
    0 讨论(0)
  • 2021-01-27 02:01

    i have a workaround.

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    lp.leftMargin = x;
    lp.topMargin = y;
    relativelayout.addView(tmpTextButtonView, lp);
    

    it is not great to use margin for positioning floating views. however it works for me.

    0 讨论(0)
提交回复
热议问题