【问题标题】:android getHeight()/getWidth with RelativeLayoutandroid getHeight()/getWidth 与 RelativeLayout
【发布时间】:2011-09-28 14:37:11
【问题描述】:

您好,我是 Android 新手,遇到了一个问题:如何获取放置在相对布局中的视图的高度/宽度?我试过 getHeight() 和 getWidth() 都返回 0。

我需要知道此视图是否已到达布局的末尾,以便我可以将下一个视图放置在其右侧或下方。

或者在不知道当前视图位置的情况下是否有更好的方法?

编辑: 我使用此代码创建一个 EditText 并将其添加到布局中:

                EditText et1 = new EditText(context);
                RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                p.addRule(RelativeLayout.RIGHT_OF,curView.getId());
                et1.setLayoutParams(p);
                et1.setId(loopid++);
                curLayout.addView(et1);
                curView=et1;

然后调用:

            int[] location=new int[2];
            curView.getLocationOnScreen(location);
            Log.d("right:", String.valueOf(location[1]));

它显示一个 0。

【问题讨论】:

  • 使用View.post(new Runnable());
  • 您能否提供更多详细信息?我是安卓新手。谢谢!
  • location[1] 是 Y 坐标,我认为您需要 X 坐标 (location[0]) [developer.android.com/reference/android/view/…]
  • 你是对的,但 location[0] 也是 0。

标签: android position android-relativelayout


【解决方案1】:

您在布局视图之前调用 getHeight()/getWidth(),因此它返回 0。如果您在生命周期的后期调用它,它将停止此问题。

【讨论】:

    【解决方案2】:

    一旦你的视图被创建,UIThread 就会膨胀它们。因此,当您实例化它们时,它们没有大小。 尝试使用

    ViewTreeObserver vto = curView.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() 
    {
        public boolean onPreDraw()
        {
            curView.getLocationOnScreen(location);
        }
    }
    

    不确定它是否会起作用

    【讨论】:

      【解决方案3】:
      final Button button = new Button(this);
      button.setText("123");
      TextPaint paint = button.getPaint();
      float len = paint.measureText(button.getText().toString());
      

      这个len会在加上一个固定值后给按钮宽度

      【讨论】:

        猜你喜欢
        • 2020-06-20
        • 2012-12-11
        • 1970-01-01
        • 2011-09-02
        • 2014-03-02
        • 1970-01-01
        • 2015-07-24
        • 2015-05-02
        • 1970-01-01
        相关资源
        最近更新 更多