View#39;s getWidth() and getHeight() returns 0(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()
太早了.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.
这篇关于View 的 getWidth() 和 getHeight() 返回 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:View 的 getWidth() 和 getHeight() 返回 0
基础教程推荐
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01