set layout margins dynamically

不羁岁月 提交于 2019-12-13 03:21:21

问题


I have a vertical layout that contains 10 relative layouts. The UX team has prepared a background with horizontal lines so I have to fit the 10 relative layout elements dynamically on the screen. I have wrote the following code to set a listener to get the vertical layout height and then to do the calculations. The problem is I get height value of -2.

    final LinearLayout layout = (LinearLayout) findViewById(R.id.fav_layout);
    final Context context = this;
    ViewTreeObserver vto = layout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {

            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)layout.getLayoutParams();
            int height = params.height;
            if (height <= 0)
                Toast.makeText(context, "measure < 0", Toast.LENGTH_SHORT).show();
            else {
                int count = layout.getChildCount();
                for (int i=0; i<count; i++){
                    RelativeLayout l = (RelativeLayout) layout.getChildAt(i);
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                    lp.setMargins(10, height/10, 0, 0);

                    l.setLayoutParams(lp);
                }       
            }
        }

    });

来源:https://stackoverflow.com/questions/20593095/set-layout-margins-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!