【发布时间】:2021-03-17 06:21:18
【问题描述】:
我有一个 6 行的“文本视图”。 当我点击每一行时,我想用 Toast 显示每行的编号。 当我使用“跨度”时,它只显示最后一个行号。 如何为 Spans 编写循环以返回所有行号。 还有其他建议吗? 感谢您的帮助。
我的代码:
public class Activity1 : AppCompatActivity
{
TextView textView;
int count = 6; //Number of lines
int next;
string txt;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
textView = FindViewById<TextView>(Resource.Id.textView1);
txt = Resources.GetString(Resource.String.test);
SpannableString ss = new SpannableString(txt);
var clickableSpan = new MyClickableSpan();
clickableSpan.Click += v => Toast.MakeText(this, "line : 1", ToastLength.Short).Show();
ss.SetSpan(clickableSpan, 0, a, SpanTypes.ExclusiveExclusive);
textView.TextFormatted = ss;
textView.MovementMethod = new LinkMovementMethod();
//For all lines
//var clickableSpan1 = new MyClickableSpan();
//var clickableSpan2 = new MyClickableSpan();
//var clickableSpan3 = new MyClickableSpan();
//var clickableSpan4 = new MyClickableSpan();
//var clickableSpan5 = new MyClickableSpan();
...
}
private class MyClickableSpan : ClickableSpan
{
public Action<View> Click;
public override void OnClick(View widget)
{
if (Click != null)
Click(widget);
}
public override void UpdateDrawState(TextPaint textPaint)
{
textPaint.UnderlineText = false;
}
}
}
我的循环代码: From this answer
for (int i = 0; i < ss.Length(); i = next)
{
// find the next span transition
next = ss.NextSpanTransition(i, ss.Length(), Class.FromType(typeof(CharacterStyle)));
// get all spans in this range
int numOfSpans = 0;
//CharacterStyle[] spans = ss.GetSpans(i, next, Class.FromType(typeof(CharacterStyle))); //return null!!!
for (int j = 0; j < count; j++)
{
numOfSpans++;
}
var clickableSpan = new MyClickableSpan();
clickableSpan.Click += v => Toast.MakeText(this, "line : " + numOfSpans, ToastLength.Short).Show(); //return last number of lines : 6
ss.SetSpan(clickableSpan, i, next, SpanTypes.ExclusiveExclusive);
textView.TextFormatted = ss;
textView.MovementMethod = new LinkMovementMethod();
}
【问题讨论】:
-
你的意思是你想得到 textview 文本的位置,就像我在下面的链接中提供的截图一样? stackoverflow.com/a/62926729/11850033
标签: android for-loop xamarin xamarin.android spannablestring