Android编程实现TextView字体颜色设置的方法小结

2019-12-10 19:50:27刘景俊

第一步:获得文本控件TextView,取名为tv

第二步:通过TextView的setTextColor方法进行文本颜色的设置,这里可以有3种方式进行设置:

第1种:

复制代码 tv.setTextColor(android.graphics.Color.RED);//系统自带的颜色类
第2种: 复制代码 tv.setTextColor(0xffff00ff);//0xffff00ff是int类型的数据 分组一下0x|ff|ff00ff,0x是代表颜色整数的标记,ff是表示透明度,ff00ff表示颜色,注意:这里ffff00ff必须是8个的颜色表示,不接受ff00ff这种6个的颜色表示。

 

第3种:

复制代码 tv.setTextColor(this.getResources().getColor(R.color.red));//通过获得资源文件进行设置。 根据不同的情况R.color.red也可以是R.string.red或者R.drawable.red,当然前提是需要在相应的配置文件里做相应的配置,如:

 

<color name="red">#FF0000</color>
<drawable name="red">#FF0000</drawable>
<string name="red">#FF0000</string>

详细的代码如下:

package yahaitt.study03_01; 
import android.app.Activity; 
import android.content.res.Resources; 
import android.graphics.Color; 
import android.os.Bundle; 
import android.widget.TextView; 
public class Study03_01 extends Activity {  
  private TextView tv; 
  @Override 
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main);  
    tv = (TextView)this.findViewById(R.id.tv01);
    //tv.setTextColor(Color.RED);
    //tv.setTextColor(0xff000000);
  } 
}

希望本文所述对大家Android程序设计有所帮助。



注:相关教程知识阅读请移步到Android开发频道。