淺入淺出Android(003):使用TextView類構造文本控件

基礎:

TextView是沒法供編輯的。
當咱們新建一個項目MyTextView時候,默認的佈局(/res/layout/activity_main.xml)中已經有了一個TextView:
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />



運行效果以下:


修改其文本內容:


在佈局文件activity_main.xml中能夠看到:
android:text="@string/hello_world"



hello_world其實是一個字符串資源,當作變量名就好了。在/res/values/strings.xml下能夠找到:
<string name="hello_world">Hello world!</string>



根據須要,修改標籤中的內容便可。

爲文本內容增長html形式的樣式:


能夠在字符串資源中添加必定的樣式,例如<i>,<b>,<u>。例如讓Hello成爲斜體:
<string name="hello_world"><i>Hello</i> world!</string>
運行結果以下:



使用Html.fromHtml爲TextView中的文本提供樣式:


爲佈局文件activity_main.xml中的TextView添加id: html

<TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />



將/src/com.example.mytextview/MainActivity.java內容更改以下:
package com.example.mytextview;

import android.os.Bundle;
import android.app.Activity;
import android.text.Html;
import android.text.Spanned;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		TextView myTextView= (TextView) findViewById(R.id.myTextView);
		Spanned sp = Html.fromHtml("<h3><u>Hello world!</u></h3>");
		myTextView.setText(sp);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}



效果以下:


使用TextView自帶的方法更改其文本內容的樣式:


例如MainActivity.java:
package com.example.mytextview;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color; //
import android.graphics.Paint; //
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		TextView myTextView= (TextView) findViewById(R.id.myTextView);
		myTextView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		myTextView.setTextSize(20);
		myTextView.setTextColor(Color.BLUE);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}



效果以下:
若是要在文本中現實<,>等特殊字符,請使用實體引用,例如&lt;等等。
相關文章
相關標籤/搜索