以前获取一个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
此方法可以一试!
时间: 2024-11-10 01:27:02