Change linear layout top margin programmatically android

后端 未结 7 1090
难免孤独
难免孤独 2021-02-01 02:31

i have two linear layouts in one frame layout.



        
7条回答
  •  天涯浪人
    2021-02-01 03:10

    Use this method to set margin in dp

    private void setMargins (View view, int left, int top, int right, int bottom) {
        if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
    
            final float scale = getBaseContext().getResources().getDisplayMetrics().density;
            // convert the DP into pixel
            int l =  (int)(left * scale + 0.5f);
            int r =  (int)(right * scale + 0.5f);
            int t =  (int)(top * scale + 0.5f);
            int b =  (int)(bottom * scale + 0.5f);
    
            p.setMargins(l, t, r, b);
            view.requestLayout();
        }
    }
    

    Call the method :

    setMargins(linearLayout,0,0,5,0);
    

    https://stackoverflow.com/a/50951911/8523391

提交回复
热议问题