简体   繁体   English

同时获取绘制阶段后两个元素的宽度

[英]Get width of two elements after the drawing phase at the same time

I have seen in the following answer: https://stackoverflow.com/a/24035591 of another post that to get the width of an element after the drawing phase I can do the following:我在以下答案中看到:另一篇文章的https://stackoverflow.com/a/24035591要在绘图阶段后获取元素的宽度,我可以执行以下操作:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity);
    View view1,view2;
    int width1,width2;´


        view1.post(() -> {
          width1=view1.getWidth();
                        }
}

What if I want to get the width of 2 elements (view1 and view2) instead of only one element as I am using both values in the same mathematical formula?如果我想获得 2 个元素(view1 和 view2)的宽度而不是一个元素的宽度,因为我在同一个数学公式中使用这两个值怎么办?

Should I do this?我应该这样做吗? --> -->

view1.post(() -> {
              width1=view1.getWidth();
              width2=view2.getWidth();
                 formula(width1,width2);
                            }

Or should I do this(I don't know if it is okay to put a runnable inside another runnable) -->或者我应该这样做(我不知道将一个 runnable 放在另一个 runnable 中是否可以)-->

view1.post(() -> {
              width1=view1.getWidth();
              view2.post(() -> {
               width2=view2.getWidth();
               formula(width1,width2);

               }
                            }

I can't do the following as I need both width's to be used in the same formula:我不能执行以下操作,因为我需要在同一个公式中使用两个宽度:

view1.post(() -> {
              width1=view1.getWidth();
                            }
view2.post(() -> {
              width2=view2.getWidth();
                            }

Both of the possibilities are working, but I would like to know which one is better or if there is another option to get both width's as I need them together as I am using them in one mathematical formula.两种可能性都有效,但我想知道哪个更好,或者是否有另一种选择来获得两个宽度,因为我需要将它们放在一起,因为我在一个数学公式中使用它们。

Note that formula(x,y) will use both width's to setMargins of another element:请注意,公式(x,y)将使用两个宽度来设置另一个元素的边距:

TextView text1;
formula(x,y){
int z = x + y;
    ConstraintLayout.LayoutParams params =(ConstraintLayout.LayoutParams) text1.getLayoutParams();
    params.setMargins(0,z,0,0);
    text1.setLayoutParams(params);
}

Please see the activity lifecycle here: https://developer.android.com/guide/components/activities/activity-lifecycle .请在此处查看活动生命周期: https://developer.android.com/guide/components/activities/activity-lifecycle

The drawing is already over when the onStart() method is called.onStart()方法时,绘图已经结束。 So you can directly call view1.getWidth() and view2.getWidth() inside this method, without using the post() call.所以你可以在这个方法中直接调用view1.getWidth()view2.getWidth() ,而不用调用post()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM