取sd卡中任意圖片設置爲所有頁面的背景圖

一、需求:

1)先預覽sd卡中的圖片;

2)選擇一張圖片;

3)設置爲所有頁面的背景圖;


二、實現步驟:

1)創建一個Android項目;

2)編寫一個Activity類,作爲完成以上功能的操作界面;(MainActivity.java)

3)編寫一個Adapter類, 用於描述圖像信息;(ImageAdapter.java)

4)編寫一個Activity類,用於測試背景設置是否ok;(OtherActivity.java)

5)編寫佈局文件 res\layout\activity_main.xml和res\layout\activity_other.xml;

6)編寫動畫配置文件res\anm\scale.xml;(不加動畫效果的話,可不寫)

7)編寫res\values\strings.xml文件;

8)AndroidManifest.xml;

9)測試


三、圖示及參考代碼:

1)項目結構圖

2)MainActivity.java

package com.example.background;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

/**
 * 簡單示例,僅供參考
 * @author huahua
 *
 */
public class MainActivity extends Activity {
    private Gallery gallery;
    private ImageSwitcher imageSwitcher;
    private Button btnGo;
    private ImageAdapter imageAdapter;
    //如果圖片是放在項目資源目錄中,則將圖片資源添加到這裏面
    private int[] resources;//=new int[]{R.drawable.mm1,R.drawable.mm2,R.drawable.mm3,R.drawable.mm4,R.drawable.mm5,R.drawable.mm6,R.drawable.tu};
    public static int resource;
    private static int index;//記住用戶預覽之後選擇的圖片序號
    public static boolean isInsdcard = true;
    private String sdcardPath; //= "/mnt/sdcard/";
    //如果圖片是放在sdcard中,則將圖片路徑添加到這裏面(調用setPaths()掃描sdcard目錄)
    private List<String> paths;
    private Drawable[] drawables;
    public static Drawable drawable;
    private Button btnOther;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        
        gallery = (Gallery)findViewById(R.id.Gallery);
        imageSwitcher = (ImageSwitcher)findViewById(R.id.ImageSwitcher);
        
        imageSwitcher.setFactory(new ViewFactory(){
            @Override
            public View makeView() {
                ImageView imageView = new ImageView(MainActivity.this);
                imageView.setBackgroundColor(0x00000000);
                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
                
                return imageView;
            }
        });
        
        //獲取圖片資源
        setPaths();
        //設置圖片資源
        setDrawables();
        if (isInsdcard){
            imageSwitcher.setImageDrawable(drawables[0]);
        } else {
            imageSwitcher.setImageResource(resources[0]);
        }
        
        btnGo = (Button)findViewById(R.id.BtnGo);
        btnGo.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                //設置當前頁面的背景圖片,並將背景圖片信息單獨保存起來    
                if (isInsdcard) {
                    findViewById(R.id.mainActivity).setBackgroundDrawable(drawables[index]);
                    drawable = drawables[index];
                } else {                        
                    findViewById(R.id.mainActivity).setBackgroundResource(resources[index]);
                    resource = resources[index];
                }
            }
        });
        
        if (isInsdcard){
            imageAdapter = new ImageAdapter(drawables, this);
        } else {            
            imageAdapter = new ImageAdapter(resources, this);
        }
        gallery.setAdapter(imageAdapter);
        gallery.setOnItemSelectedListener(new OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                if (isInsdcard){
                    imageSwitcher.setImageDrawable(drawables[position]);
                } else {                    
                    imageSwitcher.setImageResource(resources[position]);
                }
                imageSwitcher.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.scale));
                
                index = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            
            }
        });
        
        //測試:到其他頁面,看看背景是否設置ok
        btnOther = (Button)findViewById(R.id.BtnOther);
        btnOther.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, OtherActivity.class);
                MainActivity.this.startActivity(intent);
            }
        });
    }

    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    //讀取sdk上的文件,轉爲bitmap,再轉爲BitmapDrawable,此類是Drawable的子類可以直接設爲背景
    public void setDrawables(){
        drawables = new BitmapDrawable[paths.size()];
        for (int i=0; i<paths.size(); i++){
            Bitmap bitmap = BitmapFactory.decodeFile(paths.get(i));
            drawables[i] = new BitmapDrawable(getResources(), bitmap);
        }
    }
    
    //掃描sdcard目錄,將帶路徑的圖片名稱寫入集合paths中
    public void setPaths(){
        paths = new ArrayList<String>();
        sdcardPath = Environment.getExternalStorageDirectory().getPath();
        File[] fs = new File(sdcardPath).listFiles();
        for (int i=0; i<fs.length; i++){
            String path = fs[i].getPath().toLowerCase(Locale.ENGLISH);
            if (path!=null && (path.endsWith(".jpeg") || path.endsWith(".jpg") || path.endsWith(".gif"))) {
                paths.add(path);
            }
        }
    }
    
    //設置背景圖片,提供給其他Activity調用
    public static void setBackground(Activity activity, int id){
        if (isInsdcard){            
            activity.findViewById(id).setBackgroundDrawable(drawable);
        } else {
            activity.findViewById(id).setBackgroundResource(resource);
        }
    }
}

3)ImageAdapter.java

package com.example.background;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

/**
 *
 * @author huahua
 *
 */
public class ImageAdapter extends BaseAdapter{
    private int[] images;
    private Drawable[] drawables;
    private Context context;
    //private boolean isInsdcard = true;

    public ImageAdapter() {
        super();
    }

    public ImageAdapter(int[] images, Context context) {
        super();
        this.images = images;
        this.context = context;
    }
    public ImageAdapter(Drawable[] drawables, Context context) {
        super();
        this.drawables = drawables;
        this.context = context;
    }

    /**返回圖片總數*/
    @Override
    public int getCount() {
        if (MainActivity.isInsdcard) {
            return drawables.length;
        } else {            
            return images.length;
        }
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /**傳入數組id,取得待顯示的圖片的view*/
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = new ImageView(context);
        if (MainActivity.isInsdcard){
            imageView.setImageDrawable(drawables[position]);
        } else {
            imageView.setImageResource(images[position]);
        }

        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setAdjustViewBounds(true);
        
        return imageView;
    }

}

4)OtherActivity.java

package com.example.background;

import android.app.Activity;
import android.os.Bundle;

public class OtherActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        
        //在Activity中寫上這一行
        MainActivity.setBackground(this, R.id.otherActivity);
    }

}

5.1)佈局文件 res\layout\activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:id="@+id/mainActivity"
    tools:context="com.example.background.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
   <ImageSwitcher
        android:id="@+id/ImageSwitcher"
        android:layout_width="fill_parent"
        android:layout_height="125dp">
    </ImageSwitcher>
    <Gallery
        android:id="@+id/Gallery"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:layout_below="@+id/ImageSwitcher"  />
    <Button
        android:id="@+id/BtnGo"
        android:layout_width="wrap_content"
        android:layout_height="25dp"
        android:layout_below="@+id/Gallery"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="@string/btn_go" />
   <Button
        android:id="@+id/BtnOther"
        android:layout_width="120dp"
        android:layout_height="25dp"
        android:layout_below="@+id/Gallery"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="@string/btn_other" />
</RelativeLayout>

5.2)佈局文件res\layout\activity_other.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/otherActivity" >

</LinearLayout>

6)動畫配置文件res\anm\scale.xml;(不加動畫效果的話,可不寫)

<?xml version="1.0" encoding="UTF-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"  
    android:fromDegrees="0"  
    android:toDegrees="360"  
    android:pivotX="50%"  
    android:pivotY="50%"  
    android:duration="1500"  
    android:fillAfter="true">
</rotate>

7)res\values\strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Background</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="btn_go">1.設爲背景</string>
    <string name="btn_other">2.測試頁面</string>

</resources>

8)AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.background"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="OtherActivity"></activity>
    </application>

</manifest>

9)測試

9.1)上傳圖片到sd卡

9.2)測試效果圖



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章