我正在动态创建我的 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);
}
任何帮助表示赞赏。
原文由 ngreenwood6 发布,翻译遵循 CC BY-SA 4.0 许可协议
你打电话给
getWidth()
太早了。 UI 尚未在屏幕上调整大小和布局。无论如何,我怀疑你是否想做你正在做的事情——被动画化的小部件不会改变它们的可点击区域,所以按钮仍然会响应原始方向的点击,不管它是如何旋转的。
话虽如此,您可以使用 维度资源 来定义按钮大小,然后从布局文件和源代码中引用该维度资源,以避免此问题。