gpt4 book ai didi

android - 有没有办法以编程方式在 TextView 中选择文本?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:04 26 4
gpt4 key购买 nike

我有一个 TextView,我希望它允许用户搜索特定的字符串。如果找到该字符串,它应该突出显示。使用背景跨度太慢且笨拙,因此我想弄清楚是否可以让它选择字符串。我知道使用 EditText 这可以使用 setSelection(),但我不希望用户能够编辑文本,同时仍然能够手动突出显示文本,我似乎无法使用 EditText 进行管理。

我想,那就是非此即彼;是否可以以编程方式选择TextView中的文本允许选择文本而不允许在EditText?

注意:我实际上使用的是扩展 TextView 的自定义 View ,所以我假设它要么是那个,要么是扩展 EditText;我只是不确定哪个(如果有的话)会起作用。

最佳答案

不确定问题是否仍然存在,我会提供我的解决方案。也许对来自搜索引擎的人有用。

因此,据我了解,目的是选择 TextView 中的所有文本,而不能修改其内容。我没有检查它对非常大的文本有多有效,但希望不会那么糟糕。

请注意,API 版本应 >=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());
}

关于android - 有没有办法以编程方式在 TextView 中选择文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23413404/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com