SD卡图片自动播放功能实现

先贴代码:

package com.test;

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

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ToolsActivity extends Activity {
    Gallery g = null;
    List<String> it = null;// 遍历符合条件的列表
    public String actionUrl = null;
    //图片的数量 
    private int count_drawble = 0;
    //当前正在播放的图片ID
    private int cur_index = 0;
    private boolean isalive = true;// 线程循环运行的条件
    //更新条件
    private static int MSG_UPDATE = 1;
    //SD卡路径
    private final String SD_PATH = android.os.Environment

    .getExternalStorageDirectory().getAbsolutePath();

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.location_photo);
        g = (Gallery) findViewById(R.id.mygallery);
        // 添加一个ImageAdapter并设置给Gallery对象
        g.setAdapter(new ImageAdapter(this, getSD()));
        count_drawble = new ImageAdapter(this, getSD()).getCount();  
        // 设置一个itemclickListener并Toast被单击图片的位置
        g.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                Toast.makeText(ToolsActivity.this,
                        "序列:" + (position + 1) + "\n路径:" + it.get(position),
                        Toast.LENGTH_LONG).show();
            }
        });
        // 利用线程来更新 当前欲显示的图片id, 调用handler来选中当前图片
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                while (isalive) {
                    cur_index = cur_index % count_drawble; // 图片区间[0,count_drawable)

                    // msg.arg1 = cur_index
                    Message msg = mhandler.obtainMessage(MSG_UPDATE, cur_index,
                            0);
                    mhandler.sendMessage(msg);
                    //更新时间间隔为 2s
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    cur_index++; // 放置在Thread.sleep(2000)
                                    // ;防止mhandler处理消息的同步性,导致cur_index>=count_drawble
                }
            }
        }).start();
    }

    // 通过handler来更新主界面
    // mgallery.setSelection(positon),选中第position的图片,然后调用OnItemSelectedListener监听改变图像
    private Handler mhandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == MSG_UPDATE) {

                g.setSelection(msg.arg1);
                // UI Thread直接更改图片 ,不利用Gallery.OnItemSelectedListener监听更改
                // imgSwitcher.setBackgroundResource(imgAdapter.getResId(msg.arg1));
            }
        }
    };

    // 遍历SD卡中某一路径下指定类型的图片
    private List<String> getSD() {
        it = new ArrayList<String>();
        File f = new File(SD_PATH + "//" + "pictures");
        File[] files = f.listFiles();

        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (getImageFile(file.getPath()))
                it.add(file.getPath());
        }
        return it;
    }

    // 指定遍历文件类型
    private boolean getImageFile(String fName) {
        boolean re;
        String end = fName
                .substring(fName.lastIndexOf(".") + 1, fName.length())
                .toLowerCase();
        if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            re = true;
        } else {
            re = false;
        }
        return re;
    }

    // 改写BaseAdapter自定义一ImageAdapter class
    public class ImageAdapter extends BaseAdapter {
        //要是是图片的背景ID
        int mGalleryItemBackground;
        private Context mContext;
        private List<String> lis;

        public ImageAdapter(Context c, List<String> li) {
            mContext = c;
            lis = li;
            // 使用在res/values/aatrs.xml中的<declare-styleable>定义
            TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
            // 取得Gallery属性
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.Gallery_android_galleryItemBackground, 0);
            // 让对象的styleable属性能够反复使用
            a.recycle();
        }

        // 重写的方法,返回图片数目
        public int getCount() {
            return lis.size();
        }

        // 重写的方法,返回图片的数组id
        public Object getItem(int position) {
            return position;
        }

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

        // 重写的方法,返回一View对象
        public View getView(int position, View convertView, ViewGroup parent) {
            // 产生ImageView对象
            ImageView i = new ImageView(mContext);
            // 设置图片给ImageView对象
            Bitmap bm = BitmapFactory.decodeFile(lis.get(position).toString());
            i.setImageBitmap(bm);
            // 重新设置图片的宽度
            i.setScaleType(ImageView.ScaleType.CENTER);
            // 重新设置Layout的宽度
            i.setLayoutParams(new Gallery.LayoutParams(1024, 768));
            // 设置Callery背景图
            i.setBackgroundResource(mGalleryItemBackground);
            return i;
        }
    }

}


主布局:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#55000000"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="显示图片"
        android:textSize="20sp" />

    <Gallery
        android:id="@+id/mygallery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        
        android:spacing="16dp" />
 </LinearLayout>

引用样式布局:

values下的样式布局attrs.xml

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

    <declare-styleable name="Gallery">
        <attr name="android:galleryItemBackground" />
    </declare-styleable>

</resources>

代码注释已经说明问题,这里讲下流程:
首先程序读取SD卡目录下名叫pictures里面的后缀名为png,jpg,gif,jpeg,bmp的文件,返回包含每个文件路径的LIST列表。用画廊来显示特定路径的图片。

在画廊的适配器里面返回SD卡里图片的数量,和点击对应的ID。通过handle发送信心,我们选中了当前图片的消息,然后开启线程,来更新当前视图的ID。

就是模拟当前图片被选中的操作处理,当然也可以用另一种方法

 

 

posted @ 2012-07-24 15:16  神仙都是我自己  阅读(598)  评论(0编辑  收藏  举报