微信朋友圈中,如果好友发表的文字过长,会自动收缩起来,底下有提示,当点击“显示更多”时才会展开。
首先定义布局文件(很简单,不解释):
文字:
收起 显示更多
接下来就是对文字的处理,原理就是设置TextView最大行数。
先判断文字是否超过了规定的行数,如果没超过,不显现“显示更多”的文字提示。当文字超过了,就显示“显示更多”的文字提示。用户点击“显示更多”后,设置最大行数为最大。
补一句:微信的默认最大行数是10行,我这里设置是2行。你可以自行设置该值DEFAULT_MAX_LINE_COUNT。
代码如下:
public class CollapsibleTextView extends LinearLayout implements OnClickListener { /** default text show max lines */ private static final int DEFAULT_MAX_LINE_COUNT = 2; private static final int COLLAPSIBLE_STATE_NONE = 0; private static final int COLLAPSIBLE_STATE_SHRINKUP = 1; private static final int COLLAPSIBLE_STATE_SPREAD = 2; private TextView desc; private TextView descOp; private String shrinkup; private String spread; private int mState; private boolean flag; public CollapsibleTextView(Context context, AttributeSet attrs) { super(context, attrs); shrinkup = context.getString(R.string.desc_shrinkup); spread = context.getString(R.string.desc_spread); View view = inflate(context, R.layout.collapsible_textview, this); view.setPadding(0, -1, 0, 0); desc = (TextView) view.findViewById(R.id.desc_tv); descOp = (TextView) view.findViewById(R.id.desc_op_tv); descOp.setOnClickListener(this); } public CollapsibleTextView(Context context) { this(context, null); } public final void setDesc(CharSequence charSequence, BufferType bufferType) { desc.setText(charSequence, bufferType); mState = COLLAPSIBLE_STATE_SPREAD; requestLayout(); } @Override public void onClick(View v) { flag = false; requestLayout(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (!flag) { flag = true; if (desc.getLineCount() <= DEFAULT_MAX_LINE_COUNT) { mState = COLLAPSIBLE_STATE_NONE; descOp.setVisibility(View.GONE); desc.setMaxLines(DEFAULT_MAX_LINE_COUNT + 1); } else { post(new InnerRunnable()); } } } class InnerRunnable implements Runnable { @Override public void run() { if (mState == COLLAPSIBLE_STATE_SPREAD) { desc.setMaxLines(DEFAULT_MAX_LINE_COUNT); descOp.setVisibility(View.VISIBLE); descOp.setText(spread); mState = COLLAPSIBLE_STATE_SHRINKUP; } else if (mState == COLLAPSIBLE_STATE_SHRINKUP) { desc.setMaxLines(Integer.MAX_VALUE); descOp.setVisibility(View.VISIBLE); descOp.setText(shrinkup); mState = COLLAPSIBLE_STATE_SPREAD; } } }}
效果图:
代码工程: