2011-10-12 112 views
0

我正在構建一個簡單的壁紙應用程序,用戶可以通過瀏覽圖像選擇並輕鬆將其設置爲新的背景。Android - 在imageview中將當前圖像設置爲系統壁紙

我將我的drawables/images存儲在一個數組中,我不能真正包裹我的頭,以便如何以很好的方式引用imageview/array中的當前圖像。

如何更改「R.id.bSet」(在底部)以自動從我正在查看的數組中選擇圖像並將其設置爲壁紙?

package com.marcus.background; 

import java.io.IOException; 

import android.app.Activity; 
import android.app.WallpaperManager; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.ImageView; 

public class GalleryView extends Activity implements OnClickListener { 

    int pos = 0; 
    int amount = 10; 
    int max = amount - 1; 
    int min = 0; 
    Button prev, next, set; 
    ImageView image; 
    Bitmap bitmap; 
    final int[] imgs = new int[] { R.drawable.i1, R.drawable.i2, R.drawable.i3, 
      R.drawable.i4, R.drawable.i5, R.drawable.i6, R.drawable.i7, 
      R.drawable.i8, R.drawable.i9, R.drawable.i10, }; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     image = (ImageView) findViewById(R.id.iView); 
     prev = (Button) findViewById(R.id.bPrev); 
     next = (Button) findViewById(R.id.bNext); 
     set = (Button) findViewById(R.id.bSet); 
     image.setImageResource(R.drawable.i1); 
     prev.setOnClickListener(this); 
     next.setOnClickListener(this); 
     set.setOnClickListener(this); 

    } 

    public void onClick(View v) { 

     switch (v.getId()) { 
     case R.id.bPrev: 
      if (pos > min) { 
       pos--; 
       image.setImageResource(imgs[pos]); 
       ; 
      } else { 
      } 
      break; 
     case R.id.bNext: 
      if (pos < max) { 
       pos++; 
       image.setImageResource(imgs[pos]); 
       ; 
      } else { 
      } 
      break; 
     case R.id.bSet: 

      // MAGIC GOES HERE ;) 

      bitmap = BitmapFactory.decodeResource(getResources(), 
        R.drawable.i1);   
      try { 
       getApplicationContext().setWallpaper(bitmap); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      // --------------- // 

      break; 
     } 

    } 
} 

回答

1
// instead of this: 
bitmap = BitmapFactory.decodeResource(getResources(), 
        R.drawable.i1); 
// try this:  
bitmap = BitmapFactory.decodeResource(getResources(), 
        imgs[pos]); 
+0

工程就像一個魅力,非常感謝:)。不知道我是如何錯過它雖然x) – anderssonma

+0

壁紙可以設置而不裁剪? –