Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了可伸缩的textview详解(推荐)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

在Android原生的TextView的基础上,可收缩/扩展的TextView:PhilExpandableTextView。

实现原理:核心是控制TextView的max lines。在TextView的初始化阶段但尚未绘制出View的时候,使用ViewTreeObserver,监听onPreDraw事件,获取TextView正常显示需要显示的总行数,但只给TextView设置最大运行的行数(小于总行数),从而造成TextView的收缩摘要效果,当用户通过按钮或其他方式扩展时候,把TextView的最大行数设置为正常显示完全的行数+1(+1是保持余量,避免不足)。

public class MainActivity extends Activity { 
  private @R_450_10495@ng str = ""; 
 
  @Override
  protected void onCreate(Bundle savedInstanceStatE) { 
    super.onCreate(savedInstanceStatE); 
    setContentView(R.layout.activity_main); 
 
    for (int i = 0; i < 200; i++) { 
      str = str + i + " "; 
    } 
    final ExpandableTextView etv = (ExpandableTextView) findViewById(R.id.etv); 
    etv.setText(str); 
 
    Button btn = (Button) findViewById(R.id.btn); 
 
    btn.setOnClickListener(new OnClickListener() { 
 
      @Override
      public void onClick(View v) { 
        Boolean b = etv.getExpandablestatus(); 
 
        b = !b; 
        etv.setExpandable(b); 
 
      } 
    }); 
 
  } 
 
}

PhilExpandableTextView.java:

package com.ganchuanpu.ExpandableTextView; 
 
import android.content.Context; 
import android.util.AttributeSet; 
import android.view.ViewTreeObserver; 
import android.view.ViewTreeObserver.onPreDrawListener; 
import android.widget.TextView; 
import android.widget.Toast; 
 
public class ExpandableTextView extends TextView { 
 
  // 最大行,显示3行 
  private final int MAX = 3; 
  // 完全展开需要的行数 
  privatE int lines; 
 
  private ExpandableTextView mExpandableTextView; 
 
  private Boolean expandablestatus = false; 
 
  // 构造方法用两个参数的 
  public ExpandableTextView(Context context,AttributeSet attrs) { 
    super(context,attrs); 
    mExpandableTextView = this; 
    init(); 
 
  } 
 
  private void init() { 
    // 在view绘制之前的时候执行,在onDraw之前 
    ViewTreeObserver mViewTreeObserver = this.getViewTreeObserver(); 
    mViewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() { 
 
      @Override
      public Boolean onPreDraw() { 
        // 避免重复监听 
        mExpandableTextView.getViewTreeObserver().removeOnPreDrawListener(this); 
        // 获得内容行数 
        lines = getLineCount(); 
 
        return true; 
      } 
    }); 
    setExpandable(false); 
 
  } 
  // 是否展开或者收缩, 
  // true,展开; 
  // false,不展开 
 
  public void setExpandable(Boolean isExpand) { 
    if (isExpand) { 
      setMaxLines(lines + 1); 
    } else
      setMaxLines(MAX); 
 
    expandablestatus = isExpand; 
  } 
 
  public Boolean getExpandablestatus() { 
    return expandablestatus; 
  } 
 
}

可伸缩的textview详解(推荐)

以上这篇可伸缩的textview详解(推荐)就是小编分享给大家的全部内容了,希望能给大家一个,也希望大家多多支持编程小技巧。

大佬总结

以上是大佬教程为你收集整理的可伸缩的textview详解(推荐)全部内容,希望文章能够帮你解决可伸缩的textview详解(推荐)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。