안 드 로 이 드 바 이 두 이미지 보기 기능
우선,미리 보기 그림 을 표시 할 컨트롤 이 필요 합 니 다.GridView 보다 더 적합 한 것 은 없습니다.
프로필 은 다음 과 같 습 니 다:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<GridView
android:id="@+id/view_photos"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10dp"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:listSelector="@drawable/frame_select" />
</LinearLayout>
GridView 의 모든 항목 이 미리 보기 그림 입 니 다.BaseAdapter 를 계승 하여 자신의 GridImageAdapter,코드 를 실현 해 야 합 니 다.
package com.liner.manager;
import java.util.List;
import com.liner.manager.adapter.GridImageAdapter;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.AdapterView.OnItemClickListener;
public class GalleryActivity extends Activity{
private ImageButton currentImage;
private Gallery gallery;
private int[] thumbIds;
private int currentPos;
private Bitmap currentBitmap;
private List<Bitmap> bitmapCache;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
currentImage = (ImageButton)this.findViewById(R.id.image_current);
gallery = (Gallery)this.findViewById(R.id.image_gallery);
gallery.setOnItemClickListener(galleryItemClickListener);
init();
}
private OnItemClickListener galleryItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> p, View v, int position,
long id) {
//
showCurrentImage(position);
}
};
private void init(){
thumbIds = this.getIntent().getIntArrayExtra("thumbIds");
currentPos = this.getIntent().getIntExtra("currentPos",0);
//galleryIds = this.getThumbnailIds(currentPos); // gallery
bitmapCache = BitmapUtils.queryThumbnailListByIds(this, thumbIds);
GridImageAdapter adapter = new GridImageAdapter(this.getApplication(), bitmapCache);
gallery.setAdapter(adapter);
gallery.setSelection(currentPos);
showCurrentImage(currentPos);
}
private void showCurrentImage(int position){
if(currentBitmap != null){
currentBitmap.recycle();
}
currentBitmap = BitmapUtils.queryImageByThumbnailId(GalleryActivity.this, thumbIds[position]);
if(currentBitmap != null){
currentImage.setImageBitmap(currentBitmap);
}else{
//
}
//releaseBitmaps();
}
/**
* Gallery 3 , 3 , ,
* , Gallery
*/
private void releaseBitmaps(){
int start = gallery.getFirstVisiblePosition()-3; //
int end = gallery.getLastVisiblePosition()+3; //
Bitmap delBitmap;
for(int i=0; i<start; i++){
delBitmap = bitmapCache.get(i);
if(delBitmap != null){
bitmapCache.remove(i);
delBitmap.recycle();
}
}
for(int i=end+1; i<bitmapCache.size(); i++){
delBitmap = bitmapCache.get(i);
if(delBitmap != null){
bitmapCache.remove(i);
delBitmap.recycle();
}
}
}
/**
* Id Id
* @param position
* @return
*/
private Integer[] getThumbnailIds(int position){
Integer[] ids = new Integer[]{0,0,0,0,0,0,0};
int currPos = 0;
// ,
for(int i=3; i>0; i--){
if(position - i >= 0){
currPos = 3-i;
ids[currPos] = thumbIds[position-i];
}
}
ids[++currPos] = thumbIds[position]; // Id
//currGallerySelection = currPos;
// 7-currPos-1
for(int i=1; i<=6-currPos;i++){
if(position+i < thumbIds.length){
ids[currPos+i] = thumbIds[position+i];
}
}
return ids;
}
} 그 다음 에 우 리 는 Activity 에서 MediaStore 의 멀티미디어 이미지 라 이브 러 리 를 조회 하여 모든 그림 의 미리 보기 그림 을 조회 할 수 있 습 니 다.미리 보기 그림 이 있 는 위 치 는 다음 과 같 습 니 다.MediaStore.Images.Thumbnails。Activity 코드 는 다음 과 같 습 니 다.
package com.liner.manager;
import java.util.ArrayList;
import java.util.List;
import com.liner.manager.adapter.GridImageAdapter;
import android.app.Activity;
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.provider.MediaStore;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends Activity {
private GridView photoView;
private GridImageAdapter imageAdapter;
private Cursor cursor;
private int[] thumbIds;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
photoView = (GridView)this.findViewById(R.id.view_photos);
photoView.setOnItemClickListener(photoClickListener);
//showImages();
showThumbnails();
}
private void showThumbnails(){
cursor = BitmapUtils.queryThumbnails(this);
if(cursor.moveToFirst()){
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
thumbIds = new int[cursor.getCount()];
for(int i=0; i<cursor.getCount();i++){
cursor.moveToPosition(i);
String currPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
thumbIds[i] = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
Bitmap b = BitmapUtils.decodeBitmap(currPath,100,100);
bitmaps.add(b);
}
imageAdapter = new GridImageAdapter(this.getApplication(), bitmaps);
photoView.setAdapter(imageAdapter);
}
}
private AdapterView.OnItemClickListener photoClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> p, View v, int position,
long id) {
// ,
Intent intent = new Intent();
intent.setClass(MainActivity.this, GalleryActivity.class);
intent.putExtra("thumbIds", thumbIds);
intent.putExtra("currentPos", position);
startActivity(intent);
}
};
}
모든 미리 보기 그림 에 대응 하 는 id 번 호 를 기록 하고 현재 사용자 가 선택 한 위 치 를 기록 한 다음 에 Intent 를 통 해 두 번 째 디 스 플레이 인터페이스 에 전달 합 니 다.두 번 째 인터페이스의 레이아웃 파일 은 다음 과 같 습 니 다.우 리 는 Gallery 와 ImageButton 으로 이 루어 졌 습 니 다.
<?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">
<Gallery
android:id="@+id/image_gallery"
android:layout_width="fill_parent"
android:layout_height="100dp"
/>
<ImageButton
android:id="@+id/image_current"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:layout_marginTop="10dp"
/>
</LinearLayout>
그리고 이에 대응 하 는 Activity 는 다음 과 같다.
package com.liner.manager;
import java.util.List;
import com.liner.manager.adapter.GridImageAdapter;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.AdapterView.OnItemClickListener;
public class GalleryActivity extends Activity{
private ImageButton currentImage;
private Gallery gallery;
private int[] thumbIds;
private int currentPos;
private Bitmap currentBitmap;
private List<Bitmap> bitmapCache;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
currentImage = (ImageButton)this.findViewById(R.id.image_current);
gallery = (Gallery)this.findViewById(R.id.image_gallery);
gallery.setOnItemClickListener(galleryItemClickListener);
init();
}
private OnItemClickListener galleryItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> p, View v, int position,
long id) {
//
showCurrentImage(position);
}
};
private void init(){
thumbIds = this.getIntent().getIntArrayExtra("thumbIds");
currentPos = this.getIntent().getIntExtra("currentPos",0);
//galleryIds = this.getThumbnailIds(currentPos); // gallery
bitmapCache = BitmapUtils.queryThumbnailListByIds(this, thumbIds);
GridImageAdapter adapter = new GridImageAdapter(this.getApplication(), bitmapCache);
gallery.setAdapter(adapter);
gallery.setSelection(currentPos);
showCurrentImage(currentPos);
}
private void showCurrentImage(int position){
if(currentBitmap != null){
currentBitmap.recycle();
}
currentBitmap = BitmapUtils.queryImageByThumbnailId(GalleryActivity.this, thumbIds[position]);
if(currentBitmap != null){
currentImage.setImageBitmap(currentBitmap);
}else{
//
}
//releaseBitmaps();
}
}
사용자 가 Gallery 중 하 나 를 클릭 하면 onItemClick 이벤트 가 발생 합 니 다.그 중에서 저 희 는 이 미리 보기 그림 에 대응 하 는 Image 를 통 해ID 는 MediaStore.Images.Media 에서 이 미리 보기 그림 에 대응 하 는 큰 그림 을 조회 합 니 다.ImageButton 에 표 시 됩 니 다. 그림 이 많 을 때 메모리 가 넘 칠 수 있 습 니 다.이 를 피하 기 위해 Gallery 의 특징 을 살 리 고 캐 시 를 사용 할 수 있 습 니 다.현재 보 이 는 미리 보기 그림 의 앞 세 개 에서 뒤 세 개 를 저장 합 니 다.나머지 는 모두 재 활용.사용자 가 Gallery 를 클릭 할 때 현재 위 치 를 판단 하고 어떤 값 보다 크 거나 작 으 면 캐 시 를 다시 업데이트 합 니 다.메모리 의 미리 보기 그림 의 개 수 를 항상 6+Gallery.getLastVisiblePosition-gallery.getFirst VisiblePosition 개 로 확보 합 니 다.사실 이것 은 캐 시 창 을 움 직 이 는 것 입 니 다.고정 크기 의 창 이 전체 좌표(모든 미리 보기 그림)에서 움 직 입 니 다.이곳 은 실현 되 지 않 았 으 니,이후 에 계속 하 자.
또한,프로그램 에서 BitmapUtils 클래스 를 사 용 했 음 을 알 수 있 습 니 다.이 클래스 는 검색 그림 을 패키지 하고 Bitmap 클래스 로 해석 합 니 다.
코드 는 다음 과 같 습 니 다:
package com.liner.manager;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.util.Log;
public final class BitmapUtils {
public static Bitmap decodeBitmap(String path, int displayWidth, int displayHeight){
BitmapFactory.Options op = new BitmapFactory.Options();
op.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(path, op); //
//
int wRatio = (int)Math.ceil(op.outWidth/(float)displayWidth);
int hRatio = (int)Math.ceil(op.outHeight/(float)displayHeight);
// ,
if(wRatio > 1 && hRatio > 1){
if(wRatio > hRatio){
op.inSampleSize = wRatio;
}else{
op.inSampleSize = hRatio;
}
}
op.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(path, op);
return Bitmap.createScaledBitmap(bmp, displayWidth, displayHeight, true);
}
/**
*
* @param path
* @param maxImageSize
* @return
*/
public static Bitmap decodeBitmap(String path, int maxImageSize){
BitmapFactory.Options op = new BitmapFactory.Options();
op.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(path, op); //
int scale = 1;
if(op.outWidth > maxImageSize || op.outHeight > maxImageSize){
scale = (int)Math.pow(2, (int)Math.round(Math.log(maxImageSize/(double)Math.max(op.outWidth, op.outHeight))/Math.log(0.5)));
}
op.inJustDecodeBounds = false;
op.inSampleSize = scale;
bmp = BitmapFactory.decodeFile(path, op);
return bmp;
}
public static Cursor queryThumbnails(Activity context){
String[] columns = new String[]{
MediaStore.Images.Thumbnails.DATA,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.Thumbnails.IMAGE_ID
};
return context.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, columns, null, null, MediaStore.Images.Thumbnails.DEFAULT_SORT_ORDER);
}
public static Cursor queryThumbnails(Activity context, String selection, String[] selectionArgs){
String[] columns = new String[]{
MediaStore.Images.Thumbnails.DATA,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.Thumbnails.IMAGE_ID
};
return context.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, columns, selection, selectionArgs, MediaStore.Images.Thumbnails.DEFAULT_SORT_ORDER);
}
public static Bitmap queryThumbnailById(Activity context, int thumbId){
String selection = MediaStore.Images.Thumbnails._ID + " = ?";
String[] selectionArgs = new String[]{
thumbId+""
};
Cursor cursor = BitmapUtils.queryThumbnails(context,selection,selectionArgs);
if(cursor.moveToFirst()){
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
cursor.close();
return BitmapUtils.decodeBitmap(path, 100, 100);
}else{
cursor.close();
return null;
}
}
public static Bitmap[] queryThumbnailsByIds(Activity context, Integer[] thumbIds){
Bitmap[] bitmaps = new Bitmap[thumbIds.length];
for(int i=0; i<bitmaps.length; i++){
bitmaps[i] = BitmapUtils.queryThumbnailById(context, thumbIds[i]);
}
return bitmaps;
}
/**
*
* @param context
* @return
*/
public static List<Bitmap> queryThumbnailList(Activity context){
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
Cursor cursor = BitmapUtils.queryThumbnails(context);
for(int i=0; i<cursor.getCount(); i++){
cursor.moveToPosition(i);
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
Bitmap b = BitmapUtils.decodeBitmap(path, 100, 100);
bitmaps.add(b);
}
cursor.close();
return bitmaps;
}
public static List<Bitmap> queryThumbnailListByIds(Activity context, int[] thumbIds){
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
for(int i=0; i<thumbIds.length; i++){
Bitmap b = BitmapUtils.queryThumbnailById(context, thumbIds[i]);
bitmaps.add(b);
}
return bitmaps;
}
public static Cursor queryImages(Activity context){
String[] columns = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME
};
return context.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
}
public static Cursor queryImages(Activity context, String selection, String[] selectionArgs){
String[] columns = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME
};
return context.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, selection, selectionArgs, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
}
public static Bitmap queryImageById(Activity context, int imageId){
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = new String[]{
imageId + ""
};
Cursor cursor = BitmapUtils.queryImages(context, selection, selectionArgs);
if(cursor.moveToFirst()){
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
cursor.close();
//return BitmapUtils.decodeBitmap(path, 260, 260);
return BitmapUtils.decodeBitmap(path, 220); // , ,
}else{
cursor.close();
return null;
}
}
/**
* Id
* @param context
* @param thumbId
* @return
*/
public static Bitmap queryImageByThumbnailId(Activity context, Integer thumbId){
String selection = MediaStore.Images.Thumbnails._ID + " = ?";
String[] selectionArgs = new String[]{
thumbId+""
};
Cursor cursor = BitmapUtils.queryThumbnails(context, selection, selectionArgs);
if(cursor.moveToFirst()){
int imageId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
cursor.close();
return BitmapUtils.queryImageById(context, imageId);
}else{
cursor.close();
return null;
}
}
}
이렇게 하면 바 이 두 이미지 탐색 과 유사 한 효과 가 실현 된다.효과 도 는 다음 과 같다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.