我正在动态地创建我的android项目中的所有元素。我试图获得一个按钮的宽度和高度,以便我可以旋转该按钮。我只是想学习如何使用android语言。但是,它返回0。

我做了一些研究,我看到它需要在其他地方而不是在onCreate()方法中完成。如果有人能给我一个如何做这件事的例子,那就太好了。

这是我当前的代码:

package com.animation;

import android.app.Activity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;

public class AnimateScreen extends Activity {


//Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout ll = new LinearLayout(this);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(30, 20, 30, 0);

    Button bt = new Button(this);
    bt.setText(String.valueOf(bt.getWidth()));

    RotateAnimation ra = new RotateAnimation(0,360,bt.getWidth() / 2,bt.getHeight() / 2);
    ra.setDuration(3000L);
    ra.setRepeatMode(Animation.RESTART);
    ra.setRepeatCount(Animation.INFINITE);
    ra.setInterpolator(new LinearInterpolator());

    bt.startAnimation(ra);

    ll.addView(bt,layoutParams);

    setContentView(ll);
}

任何帮助都是感激的。


当前回答

如果需要在屏幕上显示某个小部件之前获取它的宽度,可以使用getMeasuredWidth()或getMeasuredHeight()。

myImage.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int width = myImage.getMeasuredWidth();
int height = myImage.getMeasuredHeight();

其他回答

如果你使用RxJava & RxBindings,一行。类似的方法没有样板。这也解决了蒂姆·奥廷(Tim Autin)的回答中隐藏警告的问题。

RxView.layoutChanges(yourView).take(1)
      .subscribe(aVoid -> {
           // width and height have been calculated here
      });

就是它了。不需要取消订阅,即使从未调用。

你可以使用addOnLayoutChangeListener

你可以在onCreate活动或onCreateView片段中使用它

@Edit 不要忘记删除它,因为在某些情况下它会触发无限循环


myView.addOnLayoutChangeListener(object : View.OnLayoutChangeListener{
                override fun onLayoutChange(
                    v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int
                ) {
                    if (v?.width > 0 && v?.height > 0){
                        // do something
                        Log.i(TAG, "view : ${view.width}")
                        // remove after finish
                        v?.removeOnLayoutChangeListener(this) 
                    }
                }
            })

正如Ian在这篇Android开发者文章中所述:

Anyhow, the deal is that layout of the contents of a window happens after all the elements are constructed and added to their parent views. It has to be this way, because until you know what components a View contains, and what they contain, and so on, there's no sensible way you can lay it out. Bottom line, if you call getWidth() etc. in a constructor, it will return zero. The procedure is to create all your view elements in the constructor, then wait for your View's onSizeChanged() method to be called -- that's when you first find out your real size, so that's when you set up the sizes of your GUI elements. Be aware too that onSizeChanged() is sometimes called with parameters of zero -- check for this case, and return immediately (so you don't get a divide by zero when calculating your layout, etc.). Some time later it will be called with the real values.

在我的例子中,我不能通过post或addOnGlobalLayoutListener获得视图的高度,它总是0。因为我的视图在一个片段中,而这个片段是MainActivity中的第二个选项卡。当我打开MainActivity时,我输入第一个选项卡,所以第二个选项卡不会显示在屏幕上。但是onGlobalLayout()或post()函数仍然有一个回调。

当第二个片段在屏幕上可见时,我得到了视图的高度。这次我得到了正确的高度。

如果你担心过度工作的onDraw方法,你可以总是设置维度为空在构造过程中,然后只设置onDraw内部的维度,如果它是空的。

这样你就不会在onDraw内部做任何工作

class myView(context:Context,attr:AttributeSet?):View(context,attr){
var height:Float?=null


override fun onDraw(canvas:Canvas){
    if (height==null){height=this.height.toFloat()}
    }
}