在Activity中的OnCreate中,获取控件TextView的width及height

在Activity的OnCreate中,即使是在setContent之后 我们也是没有办法获取到控件 例如TextView 的 长和高。

是因为,在OnCreate中,控件并没有初始化绘制出来,所以get到的width 及 height 是 0。

解决的办法的代码如下:

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		TextView tv = (TextView) findViewById(R.id.txt);
		
		// wrongMethod(tv);
		
		firstMethod(tv);
		
		// secondMethod(tv);
		
		// thirdMethod(tv);

	}

	/**
	 * 此方法有误,由于TextView都没有measure,layout完毕 也就是TextView都没有绘制完毕 所以 get到的
	 * width,height 都是 0
	 * 
	 * @param tv
	 */
	private void wrongMethod(final TextView tv) {
		int width = tv.getWidth();
		int height = tv.getHeight();

		System.out.println("----wrong-----" + "height:" + height + "	"
				+ "width:" + width);
	}

	/**
	 * 方法一
	 * @param tv
	 */
	private void firstMethod(final TextView tv) {
		ViewTreeObserver vto = tv.getViewTreeObserver();

		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				int height = tv.getMeasuredHeight();
				int width = tv.getMeasuredWidth();
				System.out.println("----first-----" + "height:" + height + "	"
						+ "width:" + width);
				setTextSize(tv, width, height);
			}
		});
	}

	/**
	 * 方法二
	 * @param tv
	 */
	private void secondMethod(final TextView tv) {
		tv.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {

			public boolean onPreDraw() {
				// 这里textView已经初始化完毕,你可以得到所有属性
				int width = tv.getHeight();
				int height = tv.getWidth();
				System.out.println("----second-----" + "height:" + height + "	"
						+ "width:" + width);
				setTextSize(tv, width, height);
				return true;
			}
		});
	}

	/**
	 * 方法三
	 * @param tv
	 */
	private void thirdMethod(final TextView tv) {
		int intw = View.MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
		int inth = View.MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);

		tv.measure(intw, inth);

		int width = tv.getMeasuredWidth();
		int height = tv.getMeasuredHeight();

		System.out.println("----third-----" + "height:" + height + "	"
				+ "width:" + width);
		
		setTextSize(tv, width, height);
	}
	
	/**
	 * 根据获取到的  width和 height 来重新设置 TextView 的 宽和高
 	 * 
	 * @param tv
	 * @param width
	 * @param height
	 */
	private void setTextSize(TextView tv, int width, int height) {
		int size = (height > width) ? height : width;
		tv.setWidth(size);
		tv.setHeight(size);
	}

}
改变前:


改变后:


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值