Android要怎麼換背景, 有兩種方式, 一種是使用底色, 一種是使用圖片,

 

Android本身預設的顏色是黑色, 如果我們想要換底色,

 

首先在res->values之下新增一個xml檔案叫做color.xml 加入以下的程式碼
<?xml version="1.0" encoding="utf-8"?>
<resources>
<drawable name="darkgray">#808080</drawable>
<drawable name="white">#FFFFFF</drawable>
<drawable name="blue">#0000FF</drawable>
</resources>


 

然後在你的main.xml(或者你的contentView的xml檔案)裡面加入


 

<LinearLayout
xmlns:android="HTTP://schemas.android.com/apk/res/android"
android:background="@drawable/white"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</LinearLayout>


 

接著將這個main.xml設定為你的contentView就可以將背景換成白色的

 

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}


 

如圖 

B2BCFB99B6DC3C520F8666B5968FBB  
 

白色好像看不見 XDDD

C6B7DCBFF93904D92049E4C6FB7DA1  


 

接下來是把自己想要的圖片變成背景 首先選好一張你想要得圖片, 假設是這張 bgbypic.png


F0DC503173E196932B0F48A319E958  

然後在res裡面建立一個資料夾叫做drawable

 

以後如果有圖檔,就都丟進這個資料夾

 

接著只要改剛剛的main.xml即可,跟改顏色的方法一樣,只是把名稱換成圖片名稱而已





 

<LinearLayout
xmlns:android="HTTP://schemas.android.com/apk/res/android"
android:background="@drawable/bgbypic"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</LinearLayout>


 

然後你就可以看到下面的畫面

D5A8442B27142ADFFDDB8498E5D2DE  


 

那如果你想要用程式碼來控制背景呢?

 

在改一下main.xml, 將LinearLayout多加上一個id屬性


 

<LinearLayout
xmlns:android="HTTP://schemas.android.com/apk/res/android"
android:background="@drawable/bgbypic"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/myLinearLayout"
>


 

然後在.java檔案裡面呼叫它就可以了

 

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearlayout = (LinearLayout) findViewById(R.id.myLinearLayout);
Resources res = this.getResources();
Drawable drawable = res.getDrawable(R.drawable.blue);
linearlayout.setBackgroundDrawable(drawable);
}
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()