当前位置:编程学习 > html/css >>

引用Drawable颜色常数及背景色

 事先将定义好的颜色代码以drawable的名称存放于resources中,这是学习开发Android程序必须养成的好习惯,正如同字符串常数一样,颜色也是可以事先在res目录下的values文件下下的colors.xml文件下定义好的,定义格式如下:
[html]  
<span style="font-size:18px;">  <drawable name=color_name>color_value</drawable></span>  
 
下面的一个例子使用两种方法使用这个定义了的常数。
方法一:通过引用的方法在xml文件下使用,使用的方法如下
[html]  
<span style="font-size:18px;"> android:background="@drawable/color_name"</span>  
 
方法二:使用java代码调用,这时需要使用如下代码
[html]  
<span style="font-size:18px;">  //获取资源的方法  
    Resources resources = getBaseContext().getResources();  
    Drawable HippoDrawable = resources.getDrawable(R.drawable.color_name);</span>  
 
下面是一个综合运用这两种方法的例子:
1.运行截图如下:
2.实现代码:
2.1 layout布局文件
[html 
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  android:orientation="vertical"  
  android:layout_width="fill_parent"  
  android:layout_height="fill_parent"  
  android:background="@drawable/red"  
  >  
  <TextView  
  android:id="@+id/myTextView01"  
  android:layout_width="fill_parent"   
  android:layout_height="wrap_content"   
  android:text="@string/str_textview01"  
  />  
  <TextView  
  android:id="@+id/myTextView02"  
  android:layout_width="fill_parent"   
  android:layout_height="wrap_content"   
  android:text="@string/str_textview02"  
  />  
</LinearLayout>  
</span>  
 
2.2 颜色资源定义文件
[html]  
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>  
<resources>  
  <drawable name="darkgray">#808080FF</drawable>  
  <drawable name="white">#FFFFFFFF</drawable>  
  <drawable name="red">#FF0000</drawable>  
</resources></span>  
 
2.3 主程序文件
[java]  
<span style="font-size:18px;">public class EX03_03 extends Activity   
{   
  private TextView mTextView01;  
  private TextView mTextView02;   
  /** Called when the activity is first created. */  
  @Override   
  public void onCreate(Bundle savedInstanceState)  
  {   
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.main);   
    mTextView01 = (TextView) findViewById(R.id.myTextView01);  
    mTextView01.setText("我是套用Drawable背景色的戴维文字。");   
      
    //获取资源的方法  
    Resources resources = getBaseContext().getResources();  
    Drawable HippoDrawable = resources.getDrawable(R.drawable.white);  
      
    mTextView01.setBackgroundDrawable(HippoDrawable);  
      
    mTextView02 = (TextView) findViewById(R.id.myTextView02);  
    mTextView02.setTextColor(Color.MAGENTA);   
    //Color类提供的颜色常量如下:  
//    Constants   
//    int BLACK    
//    int BLUE    
//    int CYAN    
//    int DKGRAY    
//    int GRAY    
//    int GREEN    
//    int LTGRAY    
//    int MAGENTA    
//    int RED    
//    int TRANSPARENT    
//    int WHITE    
//    int YELLOW   
  
    }  
  }</span>  
 
补充:web前端 , HTML/CSS  ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,