一、应用场景:设置文字字体,颜色,大小等
二、效果图:
1,“确认”前:
2,“确认”后:
三、代码:
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)this.findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO Auto-generated method stub
setTitle("button1 被您点击");
Log.i("widgetDemo", "button1 被您点击。");
//定义textView为属性为TextView,代表id为textView2的控件
TextView textView = (TextView)findViewById(R.id.textView2);
//设置内容,由于此项在@string里已经设置过,故可要可不要
textView.setText("设置文本名字颜色大小字体");
//设置颜色
textView.setTextColor(Color.RED);
//设置大小
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
//设置字体
textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
}
});
}
.xml中的配置
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="69dp"
android:text="@string/textview2" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="31dp"
android:layout_toRightOf="@+id/textView1"
android:text="@string/button1" />
string.xml:
<string name="app_name">TextViewApp</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="button1">确认</string>
<string name="textview2">设置文本</string>
四、技术总结
通过 setText() 更改 textView 的显示内容为“设置文本名字颜色大小字体”。
通过 setTextColor() 修改 textView 显示字体颜色为红色。
通过 setTextSize() 修改 textView 显示字体大小为 20sp。
通过 setTypeface() 修改 textView 显示字体风格为加粗。
也可以在.xml中设置上述内容
代码如下:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="设置文本名字颜色大小字体"
android:textColor="#ff0000"
android:textSize="20sp"
android:textStyle="bold"/>