温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

TextView文本截断与展开动画

发布时间:2024-08-21 16:11:21 来源:亿速云 阅读:78 作者:小樊 栏目:移动开发

要实现TextView文本截断与展开动画,可以通过在TextView上设置maxLines属性来控制文本的最大行数,当文本超过指定行数时,可以添加展开和收起按钮来切换文本的显示状态。

以下是一个示例代码,实现了TextView文本的截断与展开功能:

public class ExpandableTextView extends AppCompatTextView {
    private static final int DEFAULT_MAX_LINES = 3; // 默认最大行数
    private static final int ANIMATION_DURATION = 200; // 动画时长

    private int maxLines;
    private boolean isExpanded = false;

    public ExpandableTextView(Context context) {
        super(context);
        init();
    }

    public ExpandableTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
        maxLines = a.getInt(R.styleable.ExpandableTextView_maxLines, DEFAULT_MAX_LINES);
        a.recycle();
        init();
    }

    private void init() {
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggle();
            }
        });
        setMaxLines(maxLines);
    }

    private void toggle() {
        int targetLines = isExpanded ? maxLines : Integer.MAX_VALUE;
        ObjectAnimator animator = ObjectAnimator.ofInt(this, "maxLines", targetLines);
        animator.setDuration(ANIMATION_DURATION);
        animator.start();
        isExpanded = !isExpanded;
    }

    public int getMaxLines() {
        return maxLines;
    }

    public void setMaxLines(int maxLines) {
        this.maxLines = maxLines;
        super.setMaxLines(maxLines);
    }
}

在XML布局文件中使用ExpandableTextView:

<com.example.ExpandableTextView
    android:id="@+id/expandableTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Your long text here..."
    app:maxLines="3"
    android:ellipsize="end"
    android:maxLines="3"
    android:lines="3"
    android:background="@android:color/white"/>

在代码中可以动态设置ExpandableTextView的maxLines属性来控制文本的显示状态,实现文本的截断与展开效果。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI