![](/img/trans.png)
[英]the role of “this” in TextView textView = new TextView(this);
[英]Continue new line TextView after TextView
我有一個用例,當它只需要單擊一部分文本並使用不同的顏色時,在某些屏幕上,我的文本必須用兩行寫成:
使用此代碼:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton
android:id="@+id/btn_accept_terms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/selected" />
<TextView
android:id="@+id/terms1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="@+id/btn_accept_terms"
android:text="@string/txt_terms" />
<TextView
android:id="@+id/terms2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="@+id/terms1"
android:text="@string/txt_terms_hyperlink"
android:textColor="@color/colorAccent"
android:textStyle="italic"/>
</RelativeLayout>
如何實現預期的行為?
使用跨度
public static SpannableStringBuilder addClickablePart(final Context context, String str) {
int[] startIndex = {32, 73};
int[] endIndex = {45, str.length()};
SpannableStringBuilder ssb = new SpannableStringBuilder(str);
int count = 0;
while (count < 2) {
int idx1 = startIndex[count];
int idx2 = endIndex[count];
final String clickString = str.substring(idx1, idx2);
ssb.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
// Do whatever you want to do
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setColor(Color.parseColor("#ffffffff"));
}
}, idx1, idx2, 0);
count++;
}
return ssb;
}
相應地調整startIndex和endIndex
使用SpannableString
。 請參見下面的代碼。
String part1 = "By logging in, you agree to our ";
String part2 = "terms and conditions";
String fullStr = part1 + part2;
int startIndex = fullStr.indexOf(part2);
int endIndex = fullStr.length();
SpannableString styledString = new SpannableString(fullStr);
// clickable text
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(TestActivity.this, "Navigate to terms and conditions page", Toast.LENGTH_SHORT).show();
}
};
styledString.setSpan(clickableSpan, startIndex, endIndex, 0);
// set color
styledString.setSpan(new ForegroundColorSpan(Color.BLUE), startIndex, endIndex, 0);
TextView out = (TextView) findViewById(R.id.out);
out.setMovementMethod(LinkMovementMethod.getInstance());
out.setText(styledString);
要從ClickableSpan
刪除下划線,請參見此SO線程 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.