Android development skills 3-formatting TextView text and development skills textview
This example mainly studies how to display webpage links and change the specific text color in TextView.
1. main. xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/tv_url" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv_color" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="HelloWorld,HomeActivity!"/> </LinearLayout>
2. MainActivity. java:
Package com. yayun. edittextdatedemo; import android. app. activity; import android. graphics. color; import android. OS. bundle; import android. text. html; import android. text. spannable; import android. text. spannableString; import android. text. method. linkMovementMethod; import android. text. style. backgroundColorSpan; import android. text. style. foregroundColorSpan; import android. widget. textView; public class MainActivity extends Activity {private TextView mTextView1; private TextView mTextView2; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mTextView1 = (TextView) findViewById (R. id. TV _url); mTextView2 = (TextView) findViewById (R. id. TV _color); String text = "Visit <a href = \" http://www.baidu.com \ "> Baidu </a>"; mTextView1.setText (Html. fromHtml (text); // display mTextView1.setMovementMethod (LinkMovementMethod. getInstance (); // when you click a link, you must set the MovementMethod object Spannable sTextSpannable = new SpannableString (mTextView2.getText (); sTextSpannable. setSpan (new BackgroundColorSpan (Color. RED), 1, 4, 0); // spannableString. setSpan (backgroundColorSpan, start, end, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE); sTextSpannable. setSpan (new ForegroundColorSpan (Color. BLUE), 5, 9, 0); mTextView2.setText (sTextSpannable );}}
3. Run the instance:
Summary
1. Html. fromHtml (text), convert the text into html format;
2. mTextView1.setMovementMethod (LinkMovementMethod. getInstance (); // when you click a link, you must set the MovementMethod object for all actions to be executed.
3. sTextSpannable. setSpan (new BackgroundColorSpan (Color. RED), 1, 4, 0); // spannableString. setSpan (backgroundColorSpan, start, end, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE );