View的getWidth()和getHeight()返回0 [英] View's getWidth() and getHeight() returns 0

查看:321
本文介绍了View的getWidth()和getHeight()返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态创建我的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()。用户界面还没有在屏幕上进行调整和布局。

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.

这篇关于View的getWidth()和getHeight()返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆