標籤:xtend 推斷 sans etl height ota oid 邏輯 事件
正好朋友項目裡遇到了給寫了個小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);}}});}}
以下是布局介面
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/text1" android:layout_marginTop="10dp"> <TextView android:id="@+id/text2" android:layout_width="match_parent" android:layout_height="wrap_content" android:maxLines="2" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginTop="-10dp" android:text="下拉" /> </RelativeLayout></RelativeLayout>
Android在onCreate()方法中動態擷取TextView控制項的高度