简体   繁体   中英

Clickable string in textview in Android

I have added the code in strings.xml like

<string name="terms_agree_text">By Logging in, you are agreeing to our &lt;u>terms and condition&lt;/u> and &lt;u>privacy policy&lt;/u></string>

also I have added the same String in bhahasa language like this

 <string name="terms_agree_text">Dengan masuk, Anda menyatakan bahwa Anda telah menyetujui &lt;u>syarat dan ketentuan&lt;/u> dan &lt;u>kebijakan privasi&lt;/u> kami</string>

then I have set the label like this

mBinding.termsAndCondition.setText(Html.fromHtml(getString(R.string.terms_agree_text)));

Here I have to do the clickable event for this 2underline text. But, I tried to use the

sp.setSpan(click, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

But this string index is wrong for the other locale. So Currently I have added View to clickable in the text.

So can you please advise to do this. Thanks

The span must be based on a part of the string if it is meant to be a spanned area of the string. I am assuming you are attempting to hard code the starting index of the span. If you intend to do this, then you need to have a hard coded index per language and would require you to extract it to a values-en and values-jp and values-sp and every other values you support and have a dimens with <start_index_of_terms_span>40 and in the other language it would be <start_index_of_terms_span>59 for example.

However, you would need to know the index for each of the supported languages.

Why not instead just break the string up into multiple sections. Apply the color and style to the one section or phrase that is translated for terms and conditions or privacy policy instead of trying to highlight or change color of it within a larger string. This would be a much easier fix then applying a dynamic span based on all languages.

But if you must do this, then create your dimens value folder for each language and adjust the dimens value for the starting point. Or you could just cheat and check the user's language and determine which start index to use based on a large switch case per language. Either way it will be a bit messy, so it's up to you on which messy you are fine with.

Goodluck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM