解决:android TextView上响应部分文字的事件

解决:android TextView上响应部分文字的事件       

        分类:            androidjava 849人阅读 评论(0) 收藏 举报
android string layout encoding url class

运行结果如下:


TtActivity.java

public   class  TtActivity extends Activity {

     /* * Called when the activity is first created.  */
     private  TextView  tv;
     static  Context ctx = null ;
    @Override
     public   void  onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ctx = this ;
        tv  =  (TextView) findViewById(R.id.tv);
        //  String htmlLinkText= " 我的CSDN博客 ";     
      //  tv.setText(Html.fromHtml(htmlLinkText));
        tv.setMovementMethod(LinkMovementMethod.getInstance());  
        CharSequence text  =  tv.getText();  
         if (text instanceof Spannable){  
             int  end  =  text.length();  
            Spannable sp  =  (Spannable)tv.getText();  
            URLSpan[] urls = sp.getSpans( 0 , end, URLSpan. class );   
            SpannableStringBuilder style = new  SpannableStringBuilder(text);  
            style.clearSpans(); // should clear old spans   
             for (URLSpan url : urls){  
                MyURLSpan myURLSpan  =   new  MyURLSpan(url.getURL());  
                style.setSpan(myURLSpan,sp.getSpanStart(url),sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
            }  
            tv.setText(style);  
        }        
    }
   
     private   static   class  MyURLSpan extends ClickableSpan{  
         
         private  String mUrl;  
        MyURLSpan(String url) {  
            mUrl  = url;  
        }  
        @Override
         public   void  onClick(View widget) {
             //  TODO Auto-generated method stub
            Toast.makeText(ctx,  ""+mUrl ,Toast.LENGTH_SHORT).show();
        }  
    }
}

main.xml


< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >


< TextView 
android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
< /LinearLayout>


strings.xml


< resources>
     局部事件1  hello1,事件2hello2
    Tt
< /resources>

你可能感兴趣的:(Android)