2013-06-12 13 views
8

電話帳にアクセスし、ランダムな画像を選択してビューに表示する可能性はありますか?すなわち、ユーザの介入なしに、画像を選択したり、URIを送信したりすることなく、全プロセスを完了させることができる。電話帳からランダムな画像を取得して表示する

ありがとう!

+1

以下のBlackbeltなどの回答を必ず授与してください。さもなければ、貧しい人々の評判は無駄になり、誰も* sadface *のメリットはありません。 –

+0

あなたは正しいです、私は –

答えて

18

次のスニペットは、ギャラリーのコンテンツを取得し、すべてのイメージパスを配列リスト内に配置します。次に、ArrayList内のパスの1つをランダムに選択し、ImageViewのリソースとして配置します。

Handler handler = new Handler(); 

protected int counter = 0; 
private ImageView mImageView; 
private Bitmap currentBitmap = null; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.image); 
    mImageView = (ImageView) findViewById(R.id.imageView); 
    String[] projection = new String[]{ 
      MediaStore.Images.Media.DATA, 
    }; 

    Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
    Cursor cur = managedQuery(images, 
      projection, 
      "", 
      null, 
      "" 
    ); 

    final ArrayList<String> imagesPath = new ArrayList<String>(); 
    if (cur.moveToFirst()) { 

     int dataColumn = cur.getColumnIndex(
       MediaStore.Images.Media.DATA); 
     do { 
      imagesPath.add(cur.getString(dataColumn)); 
     } while (cur.moveToNext()); 
    } 
    cur.close(); 
    final Random random = new Random(); 
    final int count = imagesPath.size(); 
    handler.post(new Runnable() { 
     @Override 
     public void run() { 
      int number = random.nextInt(count); 
      String path = imagesPath.get(number); 
      if (currentBitmap != null) 
       currentBitmap.recycle(); 
       currentBitmap = BitmapFactory.decodeFile(path); 
      mImageView.setImageBitmap(currentBitmap); 
      handler.postDelayed(this, 1000); 
     } 
    }); 

} 
+0

いいコードスニペットです。 +1 – Raghunandan

+0

ありがとう@Raghunandan – Blackbelt

+0

私はまだこれをチェックする時間がなかったが、8 upvotesコードが動作すると言うので、賞金はあなたの:) 多くの多くのおかげでヘルプ! –

関連する問題