自定义View之TextView(2)

在玩手机App时我们发现,有些文字是可折叠的。当你带点击显示更多是,它会打开:点击收起它会折叠起来:处于开发者总忍不住实现一些,就自己定义了一个这样的,来玩玩看:
自定义View的内容这里不做详解!请看:点击链接:自定义View应用之TextView

这里写图片描述

1.由于文字是一行一行的显示这里我们就继承 LinearLayout吧!

代码如下:

  • public class MoreTextView extends LinearLayout{
    public MoreTextView(Context context) {
    super(context);
    init();
    }
    public MoreTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
    //自定义属性的内容
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MoreTextView);
    moreColor = a.getColor(R.styleable.MoreTextView_moreColor, Color.GRAY);
    MAX = a.getInt(R.styleable.MoreTextView_max, 15);
    if (a.getString(R.styleable.MoreTextView_hideShow) != null)
    more_hide = a.getString(R.styleable.MoreTextView_hideShow);
    if (a.getString(R.styleable.MoreTextView_moreShow) != null)
    more_show = a.getString(R.styleable.MoreTextView_moreShow);
    a.recycle();
    }

}

设置组建并初始化:

  • public void init() {
    setOrientation(VERTICAL);
    View layout = View.inflate(getContext(), R.layout.widget_moretextview, null);
    this.addView(layout);
    text = (TextView) findViewById(R.id.text);
    more = (TextView) findViewById(R.id.more);
    more.setOnClickListener(this);
    // LogUtils.e(more.getLineCount() + ” “);
    }

获取焦点:

  • @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
    //显示到屏幕上
    super.onWindowFocusChanged(hasWindowFocus);
    // LogUtils.e(“焦点改变”);
    if (text.getLineCount() == 1)
    text.setGravity(Gravity.CENTER);
    else
    text.setGravity(Gravity.LEFT);
    // text.invalidate();
    setText(text.getText().toString());
    }

设置最大多少行!

  • public void setText(String msg) {
    text.setText(msg);
    if (text.getLineCount() > MAX) {
    more.setVisibility(View.VISIBLE);
    } else
    more.setVisibility(View.INVISIBLE);
    }

点击动画:

  • @Override
    public void onClick(View view) {
    isShow = !isShow;
    if (isShow) {
    //展开
    more.setText(more_show);
    //属性动画必须有set与get方法
    ObjectAnimator.ofInt(text, “maxLines”, MAX, text.getLineCount()).setDuration(200).start();
    } else {
    //收起
    more.setText(more_hide);
    ObjectAnimator.ofInt(text, “maxLines”, text.getLineCount(), MAX).setDuration(200).start();
    }
    }

然后把这个控件放在布局里面引用就可以了:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值