View 的 getWidth() 和 getHeight() 返回 0

2022-01-30 00:00:00 android android-layout java getter

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

I am creating all of the elements in my android project dynamically. I am trying to get the width and height of a button so that I can rotate that button around. I am just trying to learn how to work with the android language. However, it returns 0.

我做了一些研究,发现它需要在 onCreate() 方法之外的其他地方完成.如果有人可以给我一个如何做的例子,那就太好了.

I did some research and I saw that it needs to be done somewhere other than in the onCreate() method. If someone can give me an example of how to do it, that would be great.

这是我当前的代码:

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);
}

感谢任何帮助.

推荐答案

你调用 getWidth() 太早了.UI 尚未在屏幕上调整大小和布局.

You are calling getWidth() too early. The UI has not been sized and laid out on the screen yet.

无论如何,我怀疑你是否想要做你正在做的事情——被动画化的小部件不会改变它们的可点击区域,因此无论按钮如何旋转,按钮仍将响应原始方向的点击.

I doubt you want to be doing what you are doing, anyway -- widgets being animated do not change their clickable areas, and so the button will still respond to clicks in the original orientation regardless of how it has rotated.

话虽如此,您可以使用 维度资源 定义按钮大小,然后从布局文件和源代码中引用该维度资源,以避免此问题.

That being said, you can use a dimension resource to define the button size, then reference that dimension resource from your layout file and your source code, to avoid this problem.

相关文章