Android在onCreate()方法中可以擷取到寬高等資訊
正好朋友項目裡遇到了給寫了個小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")@Overrideprotected 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() {@Overridepublic 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;@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubLog.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);}}});}}