视图的getWidth()和getHL.8()返回0我正在动态地创建我的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.@Overridepublic 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);}任何帮助都是非常感谢的。
4 回答
回首忆惘然
TA贡献1847条经验 获得超11个赞
@Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); //Here you can get the size! }
汪汪一只猫
TA贡献1898条经验 获得超8个赞
yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // Ensure you call it only once : yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this); // Here you can get the size :) } });
@SuppressLint("NewApi")@SuppressWarnings("deprecation")@Overridepublic void onGlobalLayout() { // Ensure you call it only once : if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } // Here you can get the size :)}
添加回答
举报
0/150
提交
取消