Không chắc liệu câu hỏi đó có còn thực tế hay không, tôi sẽ cung cấp giải pháp của mình. Có thể sẽ hữu ích cho những người đến từ các công cụ tìm kiếm.
Vì vậy, mục đích, như tôi đã hiểu, là chọn tất cả văn bản trong TextView
mà không thể sửa đổi nội dung của nó. Tôi đã không kiểm tra xem nó có hiệu quả như thế nào đối với văn bản rất lớn, nhưng hy vọng điều đó không tệ đến vậy.
Xin lưu ý, phiên bản API nên> = 11
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.Selection;
import android.text.Spannable;
import android.util.AttributeSet;
public class SelectableTextView extends TextView
{
public SelectableTextView(Context context)
{
super(context);
init();
}
public SelectableTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
public SelectableTextView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SelectableTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
{
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init()
{
if (Build.VERSION.SDK_INT > 10)
setTextIsSelectable(true);
}
@Override
public boolean onTextContextMenuItem(int id)
{
switch (id)
{
case android.R.id.cut:
return true;
case android.R.id.paste:
return true;
case android.R.id.shareText:
{
String selectedText = getText().toString().substring(getSelectionStart(), getSelectionEnd());
if (selectedText != null && !selectedText.isEmpty())
{
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, selectedText);
sendIntent.setType("text/plain");
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(sendIntent);
}
return true;
}
case android.R.id.selectAll:
{
selectAllText();
return true;
}
}
return super.onTextContextMenuItem(id);
}
public void selectAllText()
{
if (Build.VERSION.SDK_INT > 10)
Selection.setSelection((Spannable) getText(), 0, length());
}
}
Nguồn
2017-08-01 09:33:14
Nó sẽ có thể thay đổi màu sắc của một phần của chuỗi TextView. Chỉ cần sử dụng một số HTML xung quanh phần để đánh dấu và sử dụng HTML.fromHTML trong setText của bạn. Hoặc bạn có thể sử dụng một đối tượng Spannable. –
Vâng, đó là những gì tôi đã làm ban đầu, nhưng nó chậm vì văn bản lớn. – yuttadhammo
"Sử dụng nhịp nền quá chậm và khó xử" - ummmm ... thực sự? Tôi đã không nhìn thấy một vấn đề với điều này. Với [dự án mẫu này] (https://github.com/commonsguy/cw-omnibus/tree/master/RichText/Search), tôi có thể tìm kiếm sự xuất hiện của chuỗi con trong chuỗi dài hơn, xóa tất cả 'BackgroundColorSpans' hiện có và áp dụng 'BackgroundColorSpans' mới, trong 20-30ms, trong ~ 20 dòng mã. "văn bản lớn" - lớn bao nhiêu? – CommonsWare