Android开发展开收起功能
文字过长展开收起功能很普通,也很需要。
一、思路:
自定义控件MoreTextView
二、效果图:
三、关键代码:
public class MoreTextView2 extends LinearLayout {
/**
* TextView的实际高度
*/
private int textViewHeight;
/**
* 默认全文的Text
*/
private static final String EXPANDEDTEXT = "全文";
/**
* 默认收起的text
*/
private static final String COLLAPSEDTEXT = "收起";
/**
* 全文的text
*/
private String expandedText;
/**
* 收起的text
*/
private String collapsedText;
/**
* 字体大小
*/
private int textSize;
/**
* 字体颜色
*/
private int textColor;
/**
* 超过多少行出现全文、收起按钮
*/
private int trimLines;
/**
* 显示文本的TextView
*/
private TextView showTextView;
/**
* 全文和收起的TextView
*/
private TextView collapseTextView;
/**
* 是否是收起状态,默认收起
*/
private boolean collapsed = true;
private boolean show;
public MoreTextView2(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context, attrs);
}
public MoreTextView2(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MoreTextView2(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView(context, attrs);
}
private void initView(Context context, AttributeSet attrs) {
showTextView = new TextView(context);
setOrientation(VERTICAL);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MoreTextView2);
textColor = typedArray.getColor(R.styleable.MoreTextView2_textColor, Color.GRAY);
textSize = typedArray.getDimensionPixelSize(R.styleable.MoreTextView2_textSize, 14);
expandedText = typedArray.getString(R.styleable.MoreTextView2_expandedText);
if (TextUtils.isEmpty(expandedText)) {
expandedText = EXPANDEDTEXT;
}
collapsedText = typedArray.getString(R.styleable.MoreTextView2_collapsedText);
if (TextUtils.isEmpty(collapsedText)) {
collapsedText = COLLAPSEDTEXT;
}
trimLines = typedArray.getInt(R.styleable.MoreTextView2_trimLines, 0);
typedArray.recycle();
showTextView.setTextSize(textSize);
showTextView.setTextColor(textColor);
showTextView.setLineSpacing(3f, 1.2f);
//hint(没有自我介绍内容时的默认显示)
SpannableString ss = new SpannableString(getResources().getString(R.string.formal_tips));//定义hint的值
AbsoluteSizeSpan ass = new AbsoluteSizeSpan(14, true);//设置字体大小 true表示单位是sp
ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
showTextView.setHint(new SpannedString(ss));
showTextView.setHintTextColor(getResources().getColor(R.color.text_aaa));
addView(showTextView);
}
public void setText(CharSequence text) {
showTextView.setText(text);
globalLayout();
requestLayout();
invalidate();
sum();
}
四、项目demo源码结构图:
有问题或者需要完整源码看简介联系我,或者私信我