项目需求,某些textview如果超过两行,需要隐藏,右边有个图片,点击可以张开查看全部内容,也可以点击收缩。
package zivixgroup.com.skilltemp.widget;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import zivixgroup.com.skilltemp.R;
/**
* 可以伸展的textview
* Created by george.yang on 2015/8/7.
*/
public class StretchTextView extends TextView implements View.OnClickListener {
private int maxLines = 2;
private boolean isSpread;//伸展状态
private OnClickListener listener;
private int spreadHeight;//展开时的高度
public StretchTextView(Context context) {
super(context);
init(context);
}
public StretchTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public StretchTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init (Context context) {
setEllipsize(TextUtils.TruncateAt.END);//多余的变成...
setMaxLines(maxLines);
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
postDelayed(new Runnable() {
@Override
public void run() {
if (getLineCount() >= maxLines) {
setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_details_more, 0);
} else {
setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
}
}, 100);
}
});
super.setOnClickListener(this);
}
@Override
public void setOnClickListener(OnClickListener l) {
listener = l;
}
@Override
public void onClick(View view) {
if (getLineCount()<maxLines) {
return;
}
isSpread = !isSpread;
if (isSpread) {
this.setMaxLines(Integer.MAX_VALUE);
this.requestLayout();
if (spreadHeight==0) {
setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_details_more, 0);
postDelayed(new Runnable() {
@Override
public void run() {
spreadHeight = getMeasuredHeight();
resetDrawable();
}
},100);
} else {
resetDrawable();
}
} else {
this.setMaxLines(maxLines);
this.requestLayout();
spreadHeight = getMeasuredHeight();
setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_details_more, 0);
}
if (listener!=null) {
listener.onClick(view);
}
}
private void resetDrawable() {
Drawable drawable = getResources().getDrawable(R.drawable.ic_shrink_up);
drawable.setBounds(0, spreadHeight/2-drawable.getIntrinsicHeight()/2, drawable.getIntrinsicWidth(),spreadHeight/2+drawable.getIntrinsicHeight()/2);
setCompoundDrawables(null, null, drawable, null);
}
}
ic_shrink_up
ic_details_more
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u010499721/article/details/47338781