Android在onCreate()方法中动态获取TextView控件的高度

正好朋友项目里遇到了给写了个小Demo:

这个监听器看名字也知道了。就是在绘画完毕之前调用的,在这里面能够获取到行数。当然也能够获取到宽高等信息



package com.example.textviewtest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView text;
	private Button button;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		text = (TextView) findViewById(R.id.text2);
		button = (Button) findViewById(R.id.button);
		text.setText("广西新闻网-南国今报柳州讯 一消费者到发廊美发,因对美发效果不满。索要数千至1万元赔偿,并经工商调解不成,进而大"
				+ "闹发廊骚扰店主,并惊动了警方。警方介入耐心做工作,消费者在警方及工商见证后,接受店主提出的赔偿方案,两方化干戈为玉帛");
		//获取视图树的全局事件改变时得到通知
		ViewTreeObserver vto = text.getViewTreeObserver();
		//监听获取回掉函数
		vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
			@Override
			public boolean onPreDraw() {
				//获取text View 的高度
				int lineCount = text.getLineCount();
				System.out.println(lineCount);
				//逻辑推断。假设大于2显示按钮,假设行数小于或者等于2 则隐藏。

if(lineCount>2){ button.setVisibility(View.VISIBLE); }else{ button.setVisibility(View.GONE); } return true; } }); button.setOnClickListener(new OnClickListener() { Boolean flag = true; @Override public void onClick(View arg0) { // TODO Auto-generated method stub Log.i("zkk", text.getHeight() + ""); if (flag) { flag = false; text.setEllipsize(null);// 展开 text.setSingleLine(flag); button.setText("隐藏"); } else { flag = true; text.setMaxLines(2);// 收缩 button.setText("显示"); // text.setEllipsize(TruncateAt.END); } } }); } }


以下是布局界面