【轉】android:為TextView添加樣式——下划線,顏色,設置鏈接樣式及前背景色


  最近弄了弄好久沒有弄得android,幫着改一個客戶端,遇到了上面的這個問題,記下,自己用了,還是對的:

實現下划線及顏色設置:

 

public class AtActivity extends Activity {

LinearLayout ll;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ll=(LinearLayout)findViewById(R.id.ll);
        TextView tv=new TextView(this);
        
        tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划線
        tv.setText("使用代碼實現下划線樣式");
        tv.setTextColor(Color.WHITE);
        ll.addView(tv);
        
        tv=new TextView(this);
        tv.setText(Html.fromHtml("<u>使用html實現下划線樣式</u>"));
        ll.addView(tv);
 
    }
}

 

設置超鏈接樣式:默認的超鏈接是藍色的,我們現在設置成前景紅色

 

public class AtActivity extends Activity {

LinearLayout ll;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ll=(LinearLayout)findViewById(R.id.ll);
        TextView tv=new TextView(this);
        
       
        tv.setText(Html.fromHtml("<a href=\"http://blog.csdn.net/CAIYUNFREEDOM\">自定義的超鏈接樣式</a>"));
        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){     
                  URLSpan myURLSpan=   new  URLSpan(url.getURL());                        
             style.setSpan(myURLSpan,sp.getSpanStart(url),sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
             style.setSpan(new ForegroundColorSpan(Color.RED), sp.getSpanStart(url), sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//設置前景色為紅色
               } 
               tv.setText(style);   
        }
        
        ll.addView(tv);
          
        tv=new TextView(this);
        tv.setText(Html.fromHtml("<a href=\"http://blog.csdn.net/CAIYUNFREEDOM\">默認的超鏈接樣式</a>"));
        tv.setMovementMethod(LinkMovementMethod.getInstance());  
        ll.addView(tv);
 
    }
}

 

原文地址:http://blog.csdn.net/caiyunfreedom/article/details/6763834


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM