如何设置文本视图的一部分是可单击的

nar*_*esh 191 string android textview clickablespan

我有" Android是一个软件堆栈 " 的文字.在本文中,我想设置" 堆栈 "文本是可点击的.从某种意义上说,如果你点击它,它将被重定向到一个新的活动(而不是在浏览器中).

我试过但我没有得到.

dir*_*ira 503

android.text.style.ClickableSpan 可以解决你的问题.

SpannableString ss = new SpannableString("Android is a Software stack");
ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        startActivity(new Intent(MyActivity.this, NextActivity.class));
    }
    @Override
    public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setUnderlineText(false);
    }
};
ss.setSpan(clickableSpan, 22, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

TextView textView = (TextView) findViewById(R.id.hello);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);
Run Code Online (Sandbox Code Playgroud)

//在XML中:TextView:android:textColorLink ="@ drawable/your_selector"

  • 要使颜色变为蓝色,可以添加:````ForegroundColorSpan fcs = new ForegroundColorSpan(Color.BLUE); ss.setSpan(fcs,22,27,Spannable.SPAN_INCLUSIVE_INCLUSIVE);``` (14认同)
  • 这种情况发生在我的情况下,将颜色从蓝色变为其他颜色.在**设置可点击范围后,在`setSpan`**中设置`ForegroundColorSpan`.在可点击范围之前放置前景,将不会反映新颜色. (4认同)
  • 是的,您可以将多个可单击的跨度设置为可跨越的字符串. (3认同)
  • 你可以在一个文本视图中设置多个 ClickableSpan 对象吗? (2认同)
  • 感谢这一行 stextView.setMovementMethod(LinkMovementMethod.getInstance()); textView.setHighlightColor(Color.TRANSPARENT); (2认同)
  • 有没有办法在 XML 中定义可点击范围的范围?我在那里定义了字符串,并且希望在那里指定范围。 (2认同)

Pha*_*inh 72

我的功能是在里面制作多个链接 TextView

fun TextView.makeLinks(vararg links: Pair<String, View.OnClickListener>) {
    val spannableString = SpannableString(this.text)
    for (link in links) {
        val clickableSpan = object : ClickableSpan() {
            override fun onClick(view: View) {
                Selection.setSelection((view as TextView).text as Spannable, 0)
                view.invalidate()
                link.second.onClick(view)
            }
        }
        val startIndexOfLink = this.text.toString().indexOf(link.first)
        spannableString.setSpan(clickableSpan, startIndexOfLink, startIndexOfLink + link.first.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }
    this.movementMethod = LinkMovementMethod.getInstance() // without LinkMovementMethod, link can not click
    this.setText(spannableString, TextView.BufferType.SPANNABLE)
}
Run Code Online (Sandbox Code Playgroud)

使用

my_text_view.makeLinks(
        Pair("Terms of Service", View.OnClickListener {
            Toast.makeText(applicationContext, "Terms of Service Clicked", Toast.LENGTH_SHORT).show()
        }),
        Pair("Privacy Policy", View.OnClickListener {
            Toast.makeText(applicationContext, "Privacy Policy Clicked", Toast.LENGTH_SHORT).show()
        }))
Run Code Online (Sandbox Code Playgroud)

XML

<TextView
    android:id="@+id/my_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Please accept Terms of Service and Privacy Policy"
    android:textColorHighlight="#f00" // background color when pressed
    android:textColorLink="#0f0"
    android:textSize="20sp" />
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Imr*_*ana 33

您可以使用ClickableSpan的描述,在此岗位

示例代码:

TextView myTextView = new TextView(this);
String myString = "Some text [clickable]";
int i1 = myString.indexOf("[");
int i2 = myString.indexOf("]");
myTextView.setMovementMethod(LinkMovementMethod.getInstance());
myTextView.setText(myString, BufferType.SPANNABLE);
Spannable mySpannable = (Spannable)myTextView.getText();
ClickableSpan myClickableSpan = new ClickableSpan() {
   @Override
   public void onClick(View widget) { /* do something */ }
};
mySpannable.setSpan(myClickableSpan, i1, i2 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Run Code Online (Sandbox Code Playgroud)

参考


Tar*_*tlu 12

您可以使用示例代码.您想了解有关ClickableSpan的详细信息.请查看文档

  SpannableString myString = new SpannableString("This is example");

            ClickableSpan clickableSpan = new ClickableSpan() {
                    @Override
                    public void onClick(View textView) {
                        ToastUtil.show(getContext(),"Clicked Smile ");
                    }
                };

        //For Click
         myString.setSpan(clickableSpan,startIndex,lastIndex,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        //For UnderLine
         myString.setSpan(new UnderlineSpan(),startIndex,lastIndex,0);

        //For Bold
        myString.setSpan(new StyleSpan(Typeface.BOLD),startIndex,lastIndex,0);

        //Finally you can set to textView. 

        TextView textView = (TextView) findViewById(R.id.txtSpan);
        textView.setText(myString);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
Run Code Online (Sandbox Code Playgroud)


ald*_*dok 10

我做了这个帮助方法,以防有人需要从String开始和结束位置.

public static TextView createLink(TextView targetTextView, String completeString,
    String partToClick, ClickableSpan clickableAction) {

    SpannableString spannableString = new SpannableString(completeString);

    // make sure the String is exist, if it doesn't exist
    // it will throw IndexOutOfBoundException
    int startPosition = completeString.indexOf(partToClick);
    int endPosition = completeString.lastIndexOf(partToClick) + partToClick.length();

    spannableString.setSpan(clickableAction, startPosition, endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    targetTextView.setText(spannableString);
    targetTextView.setMovementMethod(LinkMovementMethod.getInstance());

    return targetTextView;
}
Run Code Online (Sandbox Code Playgroud)

以下是您如何使用它

private void initSignUp() {
    String completeString = "New to Reddit? Sign up here.";
    String partToClick = "Sign up";
    ClickableTextUtil
        .createLink(signUpEditText, completeString, partToClick,
            new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    // your action
                    Toast.makeText(activity, "Start Sign up activity",
                        Toast.LENGTH_SHORT).show();
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    // this is where you set link color, underline, typeface etc.
                    int linkColor = ContextCompat.getColor(activity, R.color.blumine);
                    ds.setColor(linkColor);
                    ds.setUnderlineText(false);
                }
            });
}
Run Code Online (Sandbox Code Playgroud)

  • 这更好,因为它考虑了本地化 (2认同)

Dan*_*ray 9

这是一种Kotlin使部分TextView可点击的方法:

private fun makeTextLink(textView: TextView, str: String, underlined: Boolean, color: Int?, action: (() -> Unit)? = null) {
    val spannableString = SpannableString(textView.text)
    val textColor = color ?: textView.currentTextColor
    val clickableSpan = object : ClickableSpan() {
        override fun onClick(textView: View) {
            action?.invoke()
        }
        override fun updateDrawState(drawState: TextPaint) {
            super.updateDrawState(drawState)
            drawState.isUnderlineText = underlined
            drawState.color = textColor
        }
    }
    val index = spannableString.indexOf(str)
    spannableString.setSpan(clickableSpan, index, index + str.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    textView.text = spannableString
    textView.movementMethod = LinkMovementMethod.getInstance()
    textView.highlightColor = Color.TRANSPARENT
}
Run Code Online (Sandbox Code Playgroud)

可以多次调用它以在 TextView 中创建多个链接:

makeTextLink(myTextView, str, false, Color.RED, action = { Log.d("onClick", "link") })
makeTextLink(myTextView, str1, true, null, action = { Log.d("onClick", "link1") })
Run Code Online (Sandbox Code Playgroud)


小智 7

 t= (TextView) findViewById(R.id.PP1);

 t.setText(Html.fromHtml("<bThis is normal text </b>" +
                "<a href=\"http://www.xyz-zyyx.com\">This is cliclable text</a> "));
 t.setMovementMethod(LinkMovementMethod.getInstance());
Run Code Online (Sandbox Code Playgroud)

  • 你能解释一下你的答案吗?解释的答案总是更好.我也编辑过,因为你的代码片段并不是格式正确. (2认同)
  • 看起来链接将指向网页,而不是 OP 请求的活动。 (2认同)

Gio*_*ino 5

我会建议一种不同的方法,我认为它需要更少的代码并且更“本地化友好”。

假设您的目标活动称为“ActivityStack”,请在清单中使用 AndroidManifest.xml 中的自定义方案(例如“myappscheme”)为其定义一个意图过滤器:

<activity
    android:name=".ActivityStack">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:host="stack"/>
        <data android:scheme="myappscheme" />
    </intent-filter>
</activity>
Run Code Online (Sandbox Code Playgroud)

定义没有任何特殊标签的 TextView(重要的是不要使用“android:autoLink”标签,请参阅:https ://stackoverflow.com/a/20647011/1699702 ):

<TextView
    android:id="@+id/stackView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/stack_string" />
Run Code Online (Sandbox Code Playgroud)

然后在 TextView 的文本中使用带有自定义方案和主机的链接(在 String.xml 中):

<string name="stack_string">Android is a Software <a href="myappscheme://stack">stack</a></string>
Run Code Online (Sandbox Code Playgroud)

并使用 setMovementMethod() 来“激活”链接(在 onCreate() 中用于活动或在 onCreateView() 中用于片段):

TextView stack = findViewById(R.id.stackView);
stack.setMovementMethod(LinkMovementMethod.getInstance());
Run Code Online (Sandbox Code Playgroud)

这将通过点击“堆栈”字样打开堆栈活动。


归档时间:

查看次数:

111124 次

最近记录:

6 年,3 月 前