您的位置:首页 > 其它

在Activity中onCreate方法里面获取空间宽度和高度的新姿势

2015-05-27 17:38 399 查看
以前获取一个View的宽度和高度,总是在Activity中的onCreate方法中获取不到,那么我们怎么在onCreate方法中获取到控件的宽度和高度呢?

方法:用View中的post方法~

代码如下:

public class MyActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final TextView textView = (TextView) findViewById(R.id.textView);

		textView.post(new Runnable() {
			@Override
			public void run() {
				Log.d("xiaoyu","--post--width:"+textView.getWidth());
				Log.d("xiaoyu","--post--height:"+textView.getHeight());
			}
		});

		Log.d("xiaoyu","--normal--width:"+textView.getWidth());
		Log.d("xiaoyu","--normal--height:"+textView.getHeight());
	}
}


布局文件:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:background="#ff0000">
    <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="#ffffff"
            android:id="@+id/textView"
            android:text="哈哈"/>
</FrameLayout>


下面贴出结果:
05-27 09:39:25.516  29819-29819/com.example.PictureAnimation D/xiaoyu﹕ --normal--width:0
05-27 09:39:25.516  29819-29819/com.example.PictureAnimation D/xiaoyu﹕ --normal--height:0
05-27 09:39:25.576  29819-29819/com.example.PictureAnimation D/xiaoyu﹕ --post--width:720
05-27 09:39:25.580  29819-29819/com.example.PictureAnimation D/xiaoyu﹕ --post--height:100


此方法可以一试!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: