您的位置:首页 > 移动开发 > Android开发

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

2017-06-25 15:57 633 查看
正好朋友项目里遇到了给写了个小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); } } }); } }


以下是布局界面


<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>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: