需要自行准备两张图片资源
public class ExpandableTextView extends TextView {
private static int MIN_LINE_NUM = 2;
private static int MAX_LINE_NUM = 20;
private int lineNum = MIN_LINE_NUM;
private boolean mIsExpanded = false;
Drawable bitmapDown;
Drawable bitmapUp;
int w, h;
/**
* 点击事件listener
*/
private OnClickListener mOnClickListener;
public ExpandableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
setMaxLines(lineNum);
bitmapDown = getResources().getDrawable(R.mipmap.down);
bitmapUp = getResources().getDrawable(R.mipmap.up);
bitmapDown.setBounds(0, 0, bitmapDown.getMinimumWidth(), bitmapDown.getMinimumHeight()); //设置边界
bitmapUp.setBounds(0, 0, bitmapUp.getMinimumWidth(), bitmapUp.getMinimumHeight()); //设置边界
super.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (lineNum == MIN_LINE_NUM) {
lineNum = MAX_LINE_NUM;
setMaxLines(lineNum);
} else {
lineNum = MIN_LINE_NUM;
setMaxLines(lineNum);
}
if (mOnClickListener != null) {
mOnClickListener.onClick(v);
}
}
});
}
@Override
public void setOnClickListener(OnClickListener listener) {
if (!isClickable()) {
setClickable(true);
}
mOnClickListener = listener;
}
@Override
public void setMaxLines(int maxlines) {
super.setMaxLines(maxlines);
if (lineNum == MAX_LINE_NUM) {
mIsExpanded = true;
} else {
mIsExpanded = false;
}
}
public boolean isExpanded() {
return mIsExpanded;
}
@Override
protected void onDraw(Canvas canvas) {
if (getLineCount() <= MIN_LINE_NUM) {
super.onDraw(canvas);
return;
}
if (lineNum == MIN_LINE_NUM) {
setCompoundDrawables(null, null, null, bitmapDown);
} else {
setCompoundDrawables(null, null,null , bitmapUp);
}
super.onDraw(canvas);
}
public void setMaxLine(int line) {
lineNum = line;
setMaxLines(line);
}
}
效果如下