main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textview" android:layout_width="200dip" android:layout_height="100dip" android:text="@string/hello_world" android:gravity="center" android:layout_centerInParent="true" /> </RelativeLayout>
MainActivity如下:
package cn.com.testviewtreeobserver1; import android.os.Bundle; import android.view.ViewTreeObserver; import android.widget.TextView; import android.app.Activity; /** * 在Activity的onCreate()方法中 * 利用ViewTreeObserver获取控件的高和宽 */ public class MainActivity extends Activity { private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ mTextView=(TextView) findViewById(R.id.textview); //在onCreate()中获取控件的方法一(不可取) int width=mTextView.getWidth(); int height=mTextView.getHeight(); System.out.println("方法一中---->width="+width+",height="+height); //在onCreate()中获取控件的方法二(可行的) ViewTreeObserver mViewTreeObserver = mTextView.getViewTreeObserver(); mViewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { int height = mTextView.getMeasuredHeight(); int width = mTextView.getMeasuredWidth(); System.out.println("方法二中---->width="+width+",height="+height); return true; } }); } }
时间: 2024-09-26 08:53:25