当前位置: 代码迷 >> Android >> 美化Android - 自动墙纸切换器(2)
  详细解决方案

美化Android - 自动墙纸切换器(2)

热度:120   发布时间:2016-05-01 15:32:07.0
美化Android - 自动墙纸切换器(二)
在前一篇博客里面,我记录了如何实现一个简单的文件浏览器,今天记录实现图片选择,预览以及墙纸切换的功能。在代码之前先看一下实现的最终效果:
图片查看器:

变更了墙纸以后的模拟器:


首先在文件浏览器的onListItemClick方法中加上图片文件的相应事件:
  protected void onListItemClick(ListView l, View v, int position, long id) {    File file = fileList.getItem(position);    if (file.isDirectory()) {      fill(file);    } else {      File[] images = file.getParentFile().listFiles(IMAGES_FILTER);      String[] files = new String[images.length];      for (int i = 0; i < images.length; i++) {        files[i] = images[i].getAbsolutePath();      }      Intent i = new Intent(this, ImageSelector.class);      i.putExtra(ImageSelector.KEY_FILES, files);      startSubActivity(i, 0);    }

这里利用Intent来转递选中的图片文件(files数组),然后调用startSubActivity方法启动ImageSelector。
ImageSelector的代码大部分是参考ApiDemo中的ImageSwitcher,所不同的是,我们要显示的资源是文件系统上的图片,而ApiDemo中是用Resource文件来作的,所以需要改写一下getView方法:
    public View getView(int position, View convertView, ViewGroup parent) {      ImageView i = new ImageView(mContext);      i.setImageDrawable(ImageSelector.buildDrawable(files[position]));      i.setAdjustViewBounds(true);      i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));      i.setBackground(android.R.drawable.picture_frame);      return i;    }


这里我被Android的API困扰了很久,原先认为API中的setImageURI方法应该就可以用文件系统上的图片作为ImageView的内容:
i.setImageURI(ContentURI.create(new File(files[position])));

但是怎么都无法生效,后来通过google找到了另外一种做法:
  private static Drawable buildDrawable(String filePath) {    InputStream is = null;    try {      URLConnection connection = new URL("file://" + filePath).openConnection();      is = connection.getInputStream();      return Drawable.createFromStream(is, filePath);///...}

具体原因是什么,只能等Google完全发表android的源代码才能知道了。

当用户点击图片的时候,设置为墙纸:
  public void onItemClick(AdapterView parent, View v, int position, long id) {    try {      URLConnection connection = new URL("file://" + files[position]).openConnection();      parent.getContext().setWallpaper(connection.getInputStream());    } catch (IOException e) {      e.printStackTrace();    }    finish();  }


这样离最终要实现的自动切换墙纸就差2个功能了:
1. 用数据库(或则其他方式)记录用户选择的多个墙纸。
2. 定时(Service)从这些墙纸中随机选择一个。
将会在后续的博客中补上,附件3是目前这些功能的所有代码,你可以下载代码在模拟器中运行,你可能还需要参考一下如何模拟SDCard这篇文章,把一些图片文件放到SDCard中,让它作为墙纸切换。
1 楼 lordhong 2007-12-09  
试试i.setImageResource(int resid)
有些method可能还没实现吧。。哈哈
2 楼 QuakeWang 2007-12-09  
我是用文件系统的图片,不是项目里面的resource,无法使用resource id
3 楼 abx01 2007-12-10  
向开拓者们学习学习
  相关解决方案