关于LayoutParams的使用

主要用来动态控制子view的摆放位置

        TextView textView = new TextView(context);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200);
        layoutParams.width=100;
        layoutParams.height=200;
        textView.setLayoutParams(layoutParams);

构造函数可是设置三种参数

  • 固定数值,单位px
  • ViewGroup.LayoutParams.MATCH_PARENT ,意思为宽度和父view相同
  • ViewGroup.LayoutParams.WRAP_CONTENT,意思为自适应

注意每个view所能获得的layoutparams都是他所对应的父view

比如textview外层包裹着的是一个linearlayout,那么

        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) textView.getLayoutParams();
        
        //设置权重比例
        layoutParams1.weight=1;
        
        //设置上部间距
        layoutParams1.topMargin=5;
        
        //设置右边间距
        layoutParams1.setMarginEnd(20);
        
        //设置四周间距
        layoutParams1.setMargins(3,3,3,3);

如果是RelativeLayout:

        RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) textView.getLayoutParams();

        //设置位置居中
        layoutParams1.addRule(RelativeLayout.CENTER_IN_PARENT);
        
        //设置在某一个id所对应的view的右边
        layoutParams1.addRule(RelativeLayout.RIGHT_OF, R.id.all);
        
        layoutParams1.topMargin=5;
        layoutParams1.setMarginEnd(20);
        layoutParams1.setMargins(3,3,3,3);
        
        layoutParams1.removeRule(RelativeLayout.CENTER_IN_PARENT);

如果是FrameLayout:

        FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) textView.getLayoutParams();
        
        //设置位置居中
        layoutParams1.gravity = Gravity.CENTER;

        layoutParams1.topMargin = 5;
        layoutParams1.setMarginEnd(20);
        layoutParams1.setMargins(3, 3, 3, 3);
    原文作者:ccccccal
    原文地址: https://www.jianshu.com/p/035f955d026b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞