本文主要是介绍自定义控件,可以伸缩的textview,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
项目需求,某些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() {@Overridepublic void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}@Overridepublic void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}@Overridepublic void afterTextChanged(Editable editable) {postDelayed(new Runnable() {@Overridepublic void run() {if (getLineCount() >= maxLines) {setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_details_more, 0);} else {setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);}}}, 100);}});super.setOnClickListener(this);}@Overridepublic void setOnClickListener(OnClickListener l) {listener = l;}@Overridepublic 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() {@Overridepublic 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
这篇关于自定义控件,可以伸缩的textview的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!