TextView進階應用程式之:實現部分文字點擊事件,textview事件

來源:互聯網
上載者:User

TextView進階應用程式之:實現部分文字點擊事件,textview事件

    有時候我們在應用中要實現一個看簡單的功能,比如在TextView上顯示了一些文字,要求文字的部分內容顏色與其它文字不同,而且競價文字點擊功能。實現也比較簡單:

public class TestActivity extends Activity {
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_test);
tv = (TextView) findViewById(R.id.text);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setText("實現點擊第2到第6個字");
CharSequence text = tv.getText();
if (text instanceof Spannable) {
SpannableStringBuilder style = new SpannableStringBuilder(text);
// style.setSpan(new ForegroundColorSpan(Color.RED),2,6,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//實現部分文字顏色改變
style.setSpan(new TestSpanClick(this), 2, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//當然這個2和6不用寫死,根據實際需要來取值
tv.setText(style);
tv.setText(style);
}
}

private static class TestSpanClick extends ClickableSpan {
private Context mContext;

public TestSpanClick(Context mContext) {
this.mContext = mContext;
}

@Override
public void onClick(View widget) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "實現部分文字點擊事件", Toast.LENGTH_SHORT).show();
}
}
}

SpannableStringBuilder 是一個什麼樣的類呢?個人覺得有一篇文章講得很詳細,我就不,文章地址:http://blog.csdn.net/lovexjyong/article/details/17021235。ClickableSpan的用法也可以參考:http://blog.csdn.net/janronehoo/article/details/7238337

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.