Android在onCreate()方法中可以擷取到寬高等資訊

來源:互聯網
上載者:User

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);}}});}}


 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.