Can I Set “android:layout_below” at Runtime Programmatically?

前端 未结 4 2073
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 11:06

Is it possible when creating a RelativeLayout at runtime to set the equivalent of android:layout_below programmatically?

相关标签:
4条回答
  • 2020-11-27 11:46

    Yes:

    RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); 
    params.addRule(RelativeLayout.BELOW, R.id.below_id);
    viewToLayout.setLayoutParams(params);
    

    First, the code creates a new layout params by specifying the height and width. The addRule method adds the equivalent of the xml properly android:layout_below. Then you just call View#setLayoutParams on the view you want to have those params.

    0 讨论(0)
  • 2020-11-27 11:55

    Kotlin version with infix function

    infix fun View.below(view: View) {
          (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
    }
    

    Then you can write:

    view1 below view2
    

    Or you can call it as a normal function:

    view1.below(view2)
    
    0 讨论(0)
  • 2020-11-27 11:58

    Alternatively you can use the views current layout parameters and modify them:

    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewToLayout.getLayoutParams();
    params.addRule(RelativeLayout.BELOW, R.id.below_id);
    
    0 讨论(0)
  • 2020-11-27 11:58

    While @jackofallcode answer is correct, it can be written in one line:

    ((RelativeLayout.LayoutParams) viewToLayout.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.below_id);
    
    0 讨论(0)
提交回复
热议问题