浅入浅出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;等等。
相关文章
相关标签/搜索