图片浏览器功能:

1、可以添加本地图片到该图片浏览器

2、添加的同时可以给图片命名

3、点击添加到列表的按钮,图片就会显示在列表界面。

4、列表界面提供图片编辑功能,包括:点击图片名称可以进行重命名,点击删除操作可以将图片从列表界面移除,点击图片缩略图可以进行该图片全屏显示。

注:该列表界面需要保存相关信息,确保每次启动该图片浏览器时列表显示的内容与上一次退出时显示的内容一致


具体实现:

1、新建项目,编写主界面布局文件  ,图片列表通过一个ListView显示

<?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:orientation="vertical" >
 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:padding="10dip"
     >
      <TextView
             android:id="@+id/textView1"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentLeft="true"
             android:text="名称:" />


         <EditText
             android:id="@+id/editName"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
       android:layout_centerInParent="true"
             android:layout_toRightOf="@id/textView1"
             android:hint="请输入图片名称"
/>
         
         <Button
             android:id="@+id/btnPickPic"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentRight="true"
             android:text="选择图片" />
     
       </RelativeLayout>
       
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:padding="10dip">


     <TextView
         android:id="@+id/label"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:text="预览图"/>


     <ImageView
         android:id="@+id/preView"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerInParent="true"
         android:maxWidth="100px"
         android:maxHeight="100px"
         android:layout_toRightOf="@id/label"/>


         <Button
             android:id="@+id/btnAdd"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentRight="true"
             android:text="加到列表" />
   
 </RelativeLayout>
       
   <ListView
       android:id="@+id/listview"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       ></ListView>
 
</LinearLayout>

2、listview.xml

<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" >


     <ImageView
         android:id="@+id/img"
         android:layout_width="80dip"
         android:layout_height="80dip"
         android:layout_alignParentLeft="true"
         android:layout_alignParentTop="true"
         android:layout_marginLeft="10dp"
         android:layout_marginTop="10dp"
         />


     <TextView
         android:id="@+id/title"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignBottom="@+id/img"
         android:layout_toRightOf="@+id/img"
         android:layout_centerVertical="true"
          />


     <Button
         android:id="@+id/view_btn"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentRight="true"
         android:layout_centerVertical="true"
         android:layout_alignTop="@+id/img"
         android:text="删除" />


 </RelativeLayout>

3、实现添加本地图片到该应用,添加按钮事件


private Button btnPicPicker; //选择图片按钮
private Button btnPicAdd;//添加到列表按钮
private Uri mPicUri;//系统返回的图片 Uri
private Cursor mPictureCursor;              //图片的明细
private TextView tvPicName;//列表中图片的名称


     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         
         btnPicPicker = (Button)findViewById(R.id.btnPickPic);
         btnPicPicker.setOnClickListener(this);
     }



     /**
      * 监听UI点击事件
      */
public void onClick(View v) {
// TODO Auto-generated method stub
int mViewId = v.getId();
switch(mViewId){
case R.id.btnPickPic:
findPicture();
break;
default:break;
}
}




/**
* 查找系统图片
*/
private void findPicture() {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,Constanse.PICTURE_SEARCHER_FLAG);
}

 }

4、返回图片后的处理 重写onActivityResult

先创建一个图片的Bean:

package com.bellsong.pv;

 import android.graphics.Bitmap;


 public class Picture {

private int id;
private String picName;
private String picUri;
private Bitmap picBitmap;


public Picture(){

}
public Picture (String picName,String picUri){
this.picName = picName;
this.picUri = picUri;
}
public String getPicName() {
return picName;
}
public void setPicName(String picName) {
this.picName = picName;
}
public String getPicUri() {
return picUri;
}
public void setPicUri(String picUri) {
this.picUri = picUri;
}
public Bitmap getPicBitmap() {
return picBitmap;
}
public void setPicBitmap(Bitmap picBitmap) {
this.picBitmap = picBitmap;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void clear(){
picName = null;
picUri = null;
picBitmap = null;
}

 }

 当前PicView16Activity: package com.bellsong.pv; 



 import java.io.FileNotFoundException; 

 import java.util.ArrayList; 

 import java.util.List; 



 // 

 //import com.bellsong.picview.DBManager; 

 //import com.bellsong.picview.Picture; 

 //import com.bellsong.picview.PicView15Activity.MyAdapter; 



 import android.app.Activity; 

 import android.content.ContentResolver; 

 import android.content.Intent; 

 import android.database.Cursor; 

 import android.graphics.Bitmap; 

 import android.graphics.BitmapFactory; 

 import android.net.Uri; 

 import android.os.Bundle; 

 import android.util.Log; 

 import android.view.View; 

 import android.view.View.OnClickListener; 

 import android.widget.Button; 

 import android.widget.ImageView; 

 import android.widget.ListView; 

 import android.widget.TextView; 



 public class PicView16Activity extends Activity implements OnClickListener { 

 

private Button btnPicPicker; 
//选择图片按钮 

private Button btnPicAdd; 
//添加到列表按钮 

private TextView tvPicName; 
//列表中图片的名称 

private ImageView ivPicPre;                 //预览图 

 

private Uri mPicUri; 
//系统返回的图片 Uri 

private Cursor mPictureCursor;              //图片的明细 



private Picture mCurrentPicture;            //当前图片 



 

 

 

     /** Called when the activity is first created. */ 

     @Override 

     public void onCreate(Bundle savedInstanceState) { 

         super.onCreate(savedInstanceState); 

         setContentView(R.layout.main); 

          

         //实例化数据 

         mCurrentPicture = new Picture(); 

          

          

         btnPicPicker = (Button)findViewById(R.id.btnPickPic); 

         ivPicPre     = (ImageView)findViewById(R.id.preView); 

         tvPicName    = (TextView)findViewById(R.id.editName); 

          

         btnPicPicker.setOnClickListener(this); 

     } 







     /** 

      * 监听UI点击事件 

      */ 

public void onClick(View v) { 

// TODO Auto-generated method stub 

int mViewId = v.getId(); 

switch(mViewId){ 

case R.id.btnPickPic: 

findPicture(); 

break; 

default:break; 

} 

} 





/** 

* 查找系统图片 

*/ 

private void findPicture() { 

// TODO Auto-generated method stub 

Intent intent = new Intent(); 

intent.setType("image/*"); 

intent.setAction(Intent.ACTION_GET_CONTENT); 

startActivityForResult(intent,Constanse.PICTURE_SEARCHER_FLAG); 

} 







/** 

* 返回图片后的处理  

* 根据uri获得图片的信息,显示在界面上 

*/ 

@Override 

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

// TODO Auto-generated method stub 

super.onActivityResult(requestCode, resultCode, data); 

 

if(requestCode == Constanse.PICTURE_SEARCHER_FLAG){ 

if(resultCode == RESULT_OK){ 

//取得图片的Uri 

mPicUri = data.getData(); 

ContentResolver mContenResolver = this.getContentResolver(); 

//解析Uri里边的信息 

   mPictureCursor = mContenResolver.query(mPicUri, null, null, null, null); 

mPictureCursor.moveToFirst(); 

 

//获取图片明细信息   ---开发时使用 

 // 
 for(int i = 0; i<mPictureCursor.getColumnCount();i++){ 

 // 
 Log.i("test",i+"-----------------"+mPictureCursor.getString(i)); 

 // 
 } 

try { 

//清空当前图片 

mCurrentPicture.clear(); 

Bitmap bitmap =BitmapFactory.decodeStream(mContenResolver.openInputStream(mPicUri)); 

mCurrentPicture.setPicBitmap(bitmap); 

String picname = mPictureCursor.getString(5); 

mCurrentPicture.setPicName(picname); 

mCurrentPicture.setPicUri(mPictureCursor.getString(1)); 

 

//显示在UI中的预览图和图片名字 

ivPicPre.setImageBitmap(bitmap); 

tvPicName.setText(picname); 

} catch (FileNotFoundException e) { 

e.printStackTrace(); 

}finally{ 

mPictureCursor.close(); 

} 

} 

} 

} 

 }


5、添加数据库

1)创建数据库,保存图片的名字 uri

DatabaseHelper.java
package com.bellsong.pv;


 import android.content.Context;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.database.sqlite.SQLiteDatabase.CursorFactory;


 public class DatabaseHelper extends SQLiteOpenHelper{




public DatabaseHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}


public DatabaseHelper(Context context) {
// TODO Auto-generated constructor stub
super(context, Constanse.DATABASE_NAME, null, Constanse.DATABASE_VERSION);
}


@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE IF NOT EXISTS pic" +  
         "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, uri VARCHAR)");  
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("ALTER TABLE pic ADD COLUMN other STRING"); 
}
 }
2)封装一个数据库工具类
package com.bellsong.pv;


 import java.util.ArrayList;
 import java.util.List;


 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
 import android.database.SQLException;
 import android.database.sqlite.SQLiteDatabase;
 import android.graphics.BitmapFactory;


 /**
  * 数据库工具类
  * @author Administrator
  *
  */
 public class DBManager {
private DatabaseHelper helper;
private SQLiteDatabase db;

/**
* @param context
* 简要说明:因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);  
* 所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里  
*/
public DBManager(Context context) {  
       helper = new DatabaseHelper(context);  
       db = helper.getWritableDatabase();  
   }  
 
/**
 * 添加图片
 * 
 */
public int addOne(Picture picture){
int tableId = -1;
db.beginTransaction();  //开始事务  
try{
ContentValues cv = new ContentValues();  
    cv.put("name", picture.getPicName()); 
    cv.put("uri", picture.getPicUri()); 
    //返回一个id,用来判断是否插入成功
    tableId = (int)db.insert("pic", null, cv);
db.setTransactionSuccessful();  //设置事务成功完成  
}
catch(SQLException e){
}
finally{
db.endTransaction();    //结束事务  
}
return tableId;
}


   /** 
    * 更新图片名称
    * @param Picture 
    */  
   public boolean updateName(Picture picture) {  
    db.beginTransaction();  //开启事务
    try{
    ContentValues cv = new ContentValues();  
    cv.put("name", picture.getPicName());  
    db.update("pic", cv, "_id = "+picture.getId(), null);  
    db.setTransactionSuccessful();  //设置事务成功完成  
    }
       catch(SQLException e){
return false;
}finally{
         db.endTransaction();    //结束事务  
       }
       return true;
   }  
     
   /** 
    * 删除图片
    * @param Picture 
    */  
   public boolean deleteOldPicture(Picture picture) {  
       
db.beginTransaction();  //开始事务  
try{
db.delete("pic", "_id = " + picture.getId(), null);  
db.setTransactionSuccessful();  //设置事务成功完成  
}
catch(SQLException e){
return false;
}
finally{
  
db.endTransaction();    //结束事务  
}
return true;
       
   }  
     
   /** 
    * 查询图片
    * @return List<Picture> 
    */  
   public List<Picture> query() {  
       ArrayList<Picture> pictures = new ArrayList<Picture>();  
       Cursor c = queryTheCursor();  
       while (c.moveToNext()) {  
           Picture picture = new Picture();  
           picture.setPicName(c.getString(c.getColumnIndex("name")));  
           picture.setPicUri(c.getString(c.getColumnIndex("uri")));
           picture.setPicBitmap(BitmapFactory.decodeFile(picture.getPicUri()));
           picture.setId(c.getInt(c.getColumnIndex("_id")));
           pictures.add(picture);  
       }  
       c.close();  
       return pictures;  
   }  
   
   /**
    * 判断是否已经存在该图片
    * @param picture
    * @return
    */
   public boolean queryIfExist(Picture picture){
    Cursor cr = db.query("pic", null, "name = ?", new String[]{picture.getPicName()}, null, null, null);
    if(cr.getCount()!=0){
    return true;
    }else{
    return false;
    }
   }
   /** 
    * 查询图片
    * @return  Cursor 
    */  
   public Cursor queryTheCursor() {  
       Cursor c = db.rawQuery("SELECT * FROM pic", null);  
       return c;  
   }  
   /** 
    * 关闭数据库 
    */  
   public void closeDB() {  
       db.close();  
   }  
 }


6、实现名字更改,动态增加删除,点击图片预览等功能

详细代码:

PicView16Activity.java
package com.bellsong.pv;


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


 import android.app.Activity;
 import android.app.AlertDialog;
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.database.Cursor;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.net.Uri;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.view.ViewGroup;
 import android.widget.BaseAdapter;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.TextView;
 import android.widget.Toast;


 public class PicView16Activity extends Activity implements OnClickListener {

private Button btnPicPicker;//选择图片按钮
private Button btnPicAdd;//添加到列表按钮
private Button btnPicDel;//删除图片按钮
private TextView tvPicName;//列表中图片的名称
private ImageView ivPicPre;                 //预览图

private ListView listview;//图片列表
private View reNameView;//重命名视图

private ImageView  img;
private TextView   title;

private Uri mPicUri;//系统返回的图片 Uri
private Cursor mPictureCursor;              //图片的明细
private DBManager mPicDatabase;//数据库操作类


private Picture mCurrentPicture;            //当前图片
private List<Picture> mData;//Adapter的数据源
private MyAdapter adapter;

private ArrayList<String> mPictureUris;//图片路径集


     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         
         //实例化数据
         mCurrentPicture = new Picture();
         mPicDatabase    = new DBManager(this);
         mData           = new ArrayList<Picture>();
         mPictureUris    = new ArrayList<String>();
         
         listview = (ListView)findViewById(R.id.listview);
         adapter  = new MyAdapter(this);
         listview.setAdapter(adapter);
         
         //异步Task查询数据库
         new LoadData().execute();
         
         
         btnPicPicker = (Button)findViewById(R.id.btnPickPic);
         btnPicAdd    = (Button)findViewById(R.id.btnAdd);
         
         ivPicPre     = (ImageView)findViewById(R.id.preView);
         tvPicName    = (TextView)findViewById(R.id.editName);
         
         
         btnPicPicker.setOnClickListener(this);
         btnPicAdd.setOnClickListener(this);
    
         
         
     }






     /**
      * 监听UI点击事件
      */
public void onClick(View v) {
// TODO Auto-generated method stub
int mViewId = v.getId();
switch(mViewId){
case R.id.btnPickPic:
findPicture();
break;
case R.id.btnAdd:
addPicture();
break;
default:break;
}
}


/**
* 添加图片到本地数据库
*/
private void addPicture() {
// TODO Auto-generated method stub
//判断图片名字和图片路径是否为空
if(!(tvPicName.getText().toString().equals("")) && mCurrentPicture.getPicUri() != null && mCurrentPicture.getPicUri().length() > 0){
//取得当前EditText中的图片名字
mCurrentPicture.setPicName(tvPicName.getText().toString());
//判断是否重命名  方法:根据名字 先查询数据库
if(!mPicDatabase.queryIfExist(mCurrentPicture)){
int mTableId = mPicDatabase.addOne(mCurrentPicture);
if(mTableId != -1 ){
Picture mPicture = new Picture();
mPicture.setId(mCurrentPicture.getId());
mPicture.setPicName(mCurrentPicture.getPicName());
mPicture.setPicBitmap(mCurrentPicture.getPicBitmap());
mPicture.setPicUri(mCurrentPicture.getPicUri());
       mData.add(mPicture);
       adapter.notifyDataSetChanged();
}else{
System.out.println("插入失败");
}
}else{
Toast.makeText(PicView16Activity.this, "该名字已存在,请重命名", Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(PicView16Activity.this, "请选择图片", Toast.LENGTH_LONG).show();

}
}


/**
* 查找系统图片
*/
private void findPicture() {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,Constanse.PICTURE_SEARCHER_FLAG);
}


public void showPicture() {
// TODO Auto-generated method stub

}



/**
* 返回图片后的处理 
* 根据uri获得图片的信息,显示在界面上
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);

if(requestCode == Constanse.PICTURE_SEARCHER_FLAG){
if(resultCode == RESULT_OK){
//取得图片的Uri
mPicUri = data.getData();
ContentResolver mContenResolver = this.getContentResolver();
//解析Uri里边的信息
   mPictureCursor = mContenResolver.query(mPicUri, null, null, null, null);
mPictureCursor.moveToFirst();

//获取图片明细信息   ---开发时使用
 // for(int i = 0; i<mPictureCursor.getColumnCount();i++){
 // Log.i("test",i+"-----------------"+mPictureCursor.getString(i));
 // }

try {
//清空当前图片
mCurrentPicture.clear();
Bitmap bitmap =BitmapFactory.decodeStream(mContenResolver.openInputStream(mPicUri));
mCurrentPicture.setPicBitmap(bitmap);
String picname = mPictureCursor.getString(5);
mCurrentPicture.setPicName(picname);
mCurrentPicture.setPicUri(mPictureCursor.getString(1));

//显示在UI中的预览图和图片名字
ivPicPre.setImageBitmap(bitmap);
tvPicName.setText(picname);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
mPictureCursor.close();
}
}
}
}


private class MyAdapter extends BaseAdapter{

private Context context;
private LayoutInflater mInflater;
 
public MyAdapter(Context context){
       this.mInflater = LayoutInflater.from(context);
       this.context = context;
   }


public int getCount() {
// TODO Auto-generated method stub
return mData.size();
}


public Picture getItem(int position) {
// TODO Auto-generated method stub
return mData.get(position);
}


public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}


public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final int selectId = position;
if(convertView == null){
convertView=mInflater.inflate(R.layout.listview, null);
}
//获得控件对象
img = (ImageView)convertView.findViewById(R.id.img);
img.setAdjustViewBounds(true);
title = (TextView)convertView.findViewById(R.id.title);
btnPicDel = (Button)convertView.findViewById(R.id.btnDel);
final Picture mPictureView = mData.get(position);


img.setImageBitmap(mPictureView.getPicBitmap());
title.setText(mPictureView.getPicName());

final int mPosition = position;
final Picture tempPicture = mPictureView;

//删除图片按钮操作
btnPicDel.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
delPictureInfo(tempPicture,selectId);
}
});

//重命名按钮操作
title.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
Log.i("bell", tempPicture.getId()+"");
reNamePicture(tempPicture,mPosition);
}
});

//预览图片按钮操作
img.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(PicView16Activity.this, PictureView.class);
for(Picture pic : mData){
mPictureUris.add(pic.getPicUri());
Log.i("bell", pic.getPicUri());
}
Log.i("bell", ""+mPictureUris.size());

Bundle bunde = new Bundle();
bunde.putStringArrayList("picUris", mPictureUris);
bunde.putInt("position", mPosition);
intent.putExtras(bunde);
startActivity(intent);
 // PicView16Activity.this.finish();

}
});

return convertView;
}





/**
* 删除图片操作
*/
public boolean delPictureInfo(final Picture mDelPicture,final int mPosition) {
// TODO Auto-generated method stub
 // final Picture mDelPicture = mData.get(position);
new AlertDialog.Builder(PicView16Activity.this)
.setTitle("通知")
.setMessage("是否删除?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.i("bell", mDelPicture.getId()+"");
if(mPicDatabase.deleteOldPicture(mDelPicture)){
Log.i("bell", "删除成功");
mData.remove(mPosition);
adapter.notifyDataSetChanged();
}
}
}).show();
return true;
}

/**
* 重命名图片
*/
public void reNamePicture(final Picture picture,final int mPosition) {
// TODO Auto-generated method stub
//引用重命名视图的布局文件
LayoutInflater inflater = (LayoutInflater)PicView16Activity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
reNameView = inflater.inflate(R.layout.rename, null);

final EditText oldName = (EditText)reNameView.findViewById(R.id.rename);
oldName.setText(picture.getPicName());

new AlertDialog.Builder(PicView16Activity.this)
.setTitle("重命名")
.setView(reNameView)
.setPositiveButton("确认",new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String rename =oldName.getText().toString().trim();//空指针异常
             Picture reNamePic = new Picture();
             reNamePic.setPicName(rename);
             reNamePic.setId(picture.getId());
             if(mPicDatabase.updateName(reNamePic)){
             mData.get(mPosition).setPicName(rename);
             adapter.notifyDataSetChanged();
             }else{
             Toast.makeText(PicView16Activity.this, "重命名不成功!", Toast.LENGTH_LONG).show();
             }
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
}).show();
}
}


/**
* 异步加载数据类
* @author Administrator
*
*/
class LoadData extends AsyncTask<Object, String, List<Picture>>{

@Override
protected List<Picture> doInBackground(Object... params) {
List<Picture> temp =mPicDatabase.query();
return temp;
}

protected void onPostExecute(final List<Picture> pictureList) {
mData.clear();
mData = pictureList;
adapter.notifyDataSetChanged();
}
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(mData != null){
mData.clear();
}
if(mPictureUris != null){
mPictureUris.clear();
}
if(listview != null){
listview.setAdapter(null);
}
mPicDatabase.closeDB();
}


 }
7、图片预览,使用gallery,实现了动态上下翻转效果
package com.bellsong.pv;


 import java.util.List;


 import android.app.Activity;
 import android.content.Context;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.animation.AccelerateInterpolator;
 import android.view.animation.Animation;
 import android.view.animation.DecelerateInterpolator;
 import android.widget.AdapterView;
 import android.widget.AdapterView.OnItemClickListener;
 import android.widget.BaseAdapter;
 import android.widget.Gallery;
 import android.widget.ImageView;


 public class PictureView extends Activity{

private Context mContext;
private List<String> mPictureUris;
private Bitmap mBitmap;
private Gallery mGallery;
private ImageView mImageView;
private int mPosition;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);

Bundle bunde = getIntent().getExtras();
mPictureUris = bunde.getStringArrayList("picUris");
mPosition    = bunde.getInt("position");
for(String uri : mPictureUris){
Log.i("note",uri+"  selectedId:"+mPosition + "  size: "+mPictureUris.size());
}

mGallery = (Gallery)findViewById(R.id.gallery);
mGallery.setAdapter(new ImageAdapter(this));

mGallery.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);

mGallery.setOnItemClickListener(new OnItemClickListener() {


public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
 // Animation myanim =AnimationUtils.loadAnimation(mContext, R.anim.myanim);
 //             view.startAnimation(myanim);

applyRotation(position, 0, 360);

}
});

}

/**
      * Setup a new 3D rotation on the container view.
      *
      * @param position the item that was clicked to show a picture, or -1 to show the list
      * @param start the start angle at which the rotation must begin
      * @param end the end angle of the rotation
      */
     private void applyRotation(int position, float start, float end) {
         // Find the center of the container
         final float centerX = mImageView.getWidth() / 2.0f;
         final float centerY = mImageView.getHeight() / 2.0f;


         // Create a new 3D rotation with the supplied parameter
         // The animation listener is used to trigger the next animation
         final Rotate3dAnimation rotation =
                 new Rotate3dAnimation(start, end, centerX, centerY, 0, false);
         rotation.setDuration(2000);//动画时间
         rotation.setFillAfter(true);//是否保存动画后的改变
         rotation.setInterpolator(new AccelerateInterpolator());//加速器
 //        rotation.setAnimationListener(new DisplayNextView(position));


         mImageView.startAnimation(rotation);
     }


     /**
      * This class listens for the end of the first half of the animation.
      * It then posts a new action that effectively swaps the views when the container
      * is rotated 90 degrees and thus invisible.
      */
     private final class DisplayNextView implements Animation.AnimationListener {
         private final int mPosition;


         private DisplayNextView(int position) {
             mPosition = position;
         }


         public void onAnimationStart(Animation animation) {
         }


         public void onAnimationEnd(Animation animation) {
 //         mImageView.post(new SwapViews(mPosition));
         }


         public void onAnimationRepeat(Animation animation) {
         }
     }
     
     
     /**
      * This class is responsible for swapping the views and start the second
      * half of the animation.
      */
     private final class SwapViews implements Runnable {
         private final int mPosition;
         public SwapViews(int position) {
             mPosition = position;
         }


         public void run() {
             final float centerX = mImageView.getWidth() / 1.0f;
             final float centerY = mImageView.getHeight() / 2.0f;
 //         final float centerX = mImageView.getWidth();
 //         final float centerY = mImageView.getHeight();
             Rotate3dAnimation rotation;
 //            
 //            if (mPosition > -1) {
 //                mImageView.setVisibility(View.VISIBLE);
 //                mImageView.requestFocus();


                 rotation = new Rotate3dAnimation(0, 360, centerX, centerY,  0, false);
 //            } else {
 //                mImageView.setVisibility(View.GONE);


 //                rotation = new Rotate3dAnimation(90, 0, centerX, centerY, 310.0f, false);
 //            }


             rotation.setDuration(2000);
             rotation.setFillAfter(true);
             rotation.setInterpolator(new DecelerateInterpolator());
             mImageView.startAnimation(rotation);
         }
     }


public class ImageAdapter extends BaseAdapter{
private Context mContext;

public ImageAdapter(Context context){
mContext = context;

}


public int getCount() {
// TODO Auto-generated method stub
return mPictureUris.size();
}


public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}


public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}


public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
mImageView  = new ImageView(mContext);
 // mImageView.setImageBitmap(BitmapFactory.decodeFile(mPictureUris.get(mPosition)));
mBitmap = BitmapFactory.decodeFile(mPictureUris.get(position));


mImageView.setImageBitmap(mBitmap);
mImageView.setScaleType(ImageView.ScaleType.CENTER);
mImageView.setLayoutParams(new Gallery.LayoutParams(400,500));
return mImageView;
}

}


@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(mPictureUris != null){
mPictureUris.clear();
}
}


 }
动画类,直接从ApiDemo中 copy Rotate3dAnimation.java
/*
  * Copyright (C) 2007 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */


 package com.bellsong.pv;


 import android.view.animation.Animation;
 import android.view.animation.Transformation;
 import android.graphics.Camera;
 import android.graphics.Matrix;


 /**
  * An animation that rotates the view on the Y axis between two specified angles.
  * This animation also adds a translation on the Z axis (depth) to improve the effect.
  */
 public class Rotate3dAnimation extends Animation {
     private final float mFromDegrees;
     private final float mToDegrees;
     private final float mCenterX;
     private final float mCenterY;
     private final float mDepthZ;
     private final boolean mReverse;
     private Camera mCamera;


     /**
      * Creates a new 3D rotation on the X axis. The rotation is defined by its
      * start angle and its end angle. Both angles are in degrees. The rotation
      * is performed around a center point on the 2D space, definied by a pair
      * of X and Y coordinates, called centerX and centerY. When the animation
      * starts, a translation on the Z axis (depth) is performed. The length
      * of the translation can be specified, as well as whether the translation
      * should be reversed in time.
      *
      * @param fromDegrees the start angle of the 3D rotation
      * @param toDegrees the end angle of the 3D rotation
      * @param centerX the X center of the 3D rotation
      * @param centerY the Y center of the 3D rotation
      * @param reverse true if the translation should be reversed, false otherwise
      */
     public Rotate3dAnimation(float fromDegrees, float toDegrees,
             float centerX, float centerY, float depthZ, boolean reverse) {
         mFromDegrees = fromDegrees;
         mToDegrees = toDegrees;
         mCenterX = centerX;
         mCenterY = centerY;
         mDepthZ = depthZ;
         mReverse = reverse;
     }


     @Override
     public void initialize(int width, int height, int parentWidth, int parentHeight) {
         super.initialize(width, height, parentWidth, parentHeight);
         mCamera = new Camera();
     }


     @Override
     protected void applyTransformation(float interpolatedTime, Transformation t) {
         final float fromDegrees = mFromDegrees;
         float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);


         final float centerX = mCenterX;
         final float centerY = mCenterY;
         final Camera camera = mCamera;


         final Matrix matrix = t.getMatrix();


         camera.save();
         if (mReverse) {
             camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
         } else {
             camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
         }
         camera.rotateX(degrees);//以X轴
         camera.getMatrix(matrix);
         camera.restore();


         matrix.preTranslate(-centerX, -centerY);
         matrix.postTranslate(centerX, centerY);
     }
 }

gallery.xml
<Gallery xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:spacing="150dp"
android:unselectedAlpha="1.2"
 />rename.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" 
     >


     <TextView 
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:text="图片名称:"
         />
     <EditText 
         android:id="@+id/rename"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
             />


 </LinearLayout>
main.xml

<?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:orientation="vertical" >
 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:padding="10dip"
     >
      <TextView
             android:id="@+id/textView1"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentLeft="true"
             android:text="名称:" />


         <EditText
             android:id="@+id/editName"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
       android:layout_centerInParent="true"
             android:layout_toRightOf="@id/textView1"
             android:hint="请输入图片名称"
/>
         
         <Button
             android:id="@+id/btnPickPic"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentRight="true"
             android:text="选择图片" />
     
       </RelativeLayout>
       
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:padding="10dip">


     <TextView
         android:id="@+id/label"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:text="预览图"/>


     <ImageView
         android:id="@+id/preView"
         android:layout_width="100px"
         android:layout_height="100px"
         android:layout_centerInParent="true"
         android:maxWidth="100px"
         android:maxHeight="100px"
         android:layout_toRightOf="@id/label"/>


         <Button
             android:id="@+id/btnAdd"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentRight="true"
             android:text="加到列表" />
   
 </RelativeLayout>
       
   <ListView
       android:id="@+id/listview"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       ></ListView>
 
</LinearLayout>
listview.xml
<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" >


     <ImageView
         android:id="@+id/img"
         android:layout_width="80dip"
         android:layout_height="80dip"
         android:layout_alignParentLeft="true"
         android:layout_alignParentTop="true"
         android:layout_marginLeft="10dp"
         android:layout_marginTop="10dp"
         />


     <TextView
         android:id="@+id/title"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignBottom="@+id/img"
         android:layout_toRightOf="@+id/img"
         android:layout_centerVertical="true"
         android:layout_marginLeft="20dp"
          />


     <Button
         android:id="@+id/btnDel"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentRight="true"
         android:layout_centerVertical="true"
         android:layout_alignTop="@+id/img"
         android:layout_marginTop="25dp"
         android:text="删除" />


 </RelativeLayout>



8、未解决问题

如何实现点击图片跳到gallery时不是从第一个开始显示,而是默认显示选中那个。

增加手势功能,实现随手势上下滑动不停翻转,并且有加速度,当不滑动时,图片有个慢慢停下来的动作