可以使用自定义的TextView并结合TextWatcher实现该功能。首先,重写TextView的onTextChanged方法,在其中通过计算当前文本宽度和TextView的宽度得出是否需要自动换行。如果需要,就在当前光标位置插入一个换行符。代码示例如下:
public class WrapContentTextView extends TextView {
private int mLastWidth = 0;
public WrapContentTextView(Context context, AttributeSet attrs) {
super(context, attrs);
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
if (getWidth() == mLastWidth) {
return;
mLastWidth = getWidth();
int lineCount = getLineCount();
int lineHeight = getHeight() / lineCount;
Layout layout = getLayout();
int lastLineStart = layout.getLineStart(lineCount - 1);
int lastLineEnd = layout.getLineEnd(lineCount - 1);
int lastLineWidth = (int) layout.getLineWidth(lineCount - 1);
if (lastLineWidth > getWidth()) {
String newText = text.subSequence(0, lastLineStart) + "\n" + text.subSequence(lastLineStart, text.length());
setText(newText);
setSelection(lastLineStart + 1);
然后在Activity中使用这个自定义的TextView,并添加TextWatcher监听器,如下所示:
WrapContentTextView textView = findViewById(R.id.text_view);
textView.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) {
// do something
@Override
public void afterTextChanged(Editable editable) {
// do something
这样,在TextView的文本内容发生改变时,会自动进行换行。