gpt4 book ai didi

java - 通过单击异步 gridview 中的图像来防止在访问上下文操作菜单时重新加载 Activity

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:15:47 26 4
gpt4 key购买 nike

我有一堆来自 sdcard 的图像,它们在 gridview 上异步加载。一切正常,但是当通过长按任何图像访问多选上下文操作菜单时,整个 Activity 会重新加载,所有图像都会重新加载。如何预防?

我的适配器

public class PhotosGridViewImageAdapter extends BaseAdapter {

AsyncTaskLoadFiles myAsyncTaskLoadFiles;

public class AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> {

File targetDirector;
PhotosGridViewImageAdapter myTaskAdapter;

public AsyncTaskLoadFiles(PhotosGridViewImageAdapter adapter) {
myTaskAdapter = adapter;
}

@Override
protected void onPreExecute() {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + File.separator + AppConstant.PHOTO_ALBUM + File.separator;
targetDirector = new File(targetPath);
myTaskAdapter.clear();

super.onPreExecute();
}

@Override
protected Void doInBackground(Void... params) {
File[] files = targetDirector.listFiles();
Arrays.sort(files);
for (File file : files) {
publishProgress(file.getAbsolutePath());
if (isCancelled()) break;
}
return null;
}

@Override
protected void onProgressUpdate(String... values) {
myTaskAdapter.add(values[0]);
super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(Void result) {
myTaskAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}

}

ArrayList<String> itemList = new ArrayList<String>();

void add(String path) {
itemList.add(path);
}

void clear() {
itemList.clear();
}

void remove(int index){
itemList.remove(index);
}

private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;

public PhotosGridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
}

@Override
public int getCount() {
return this._filePaths.size();
}

@Override
public Object getItem(int position) {
return this._filePaths.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));

convertView = imageView;

holder = new ViewHolder();
holder.image = imageView;
holder.position = position;
convertView.setTag(holder);
} else {
//imageView = (ImageView) convertView;
holder = (ViewHolder) convertView.getTag();
((ImageView)convertView).setImageBitmap(null);
}

new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;

// get screen dimensions
@Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
imageWidth);
//imageView.setImageBitmap(image);
return image;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
v.image.setImageBitmap(result);

}
}.execute(holder);

return convertView;
}

/*
* Resizing image size
*/
public Bitmap decodeFile(String filePath, int WIDTH, int HEIGHT) {
try {
File f = new File(filePath);
if(filePath.contains(".jpg")) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);

final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HEIGHT = HEIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HEIGHT)
scale *= 2;

BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}else if(filePath.contains(".mp4")){
return ThumbnailUtils.createVideoThumbnail(filePath, 0);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
class ViewHolder {
ImageView image;
int position;
}
}

上下文操作菜单代码

public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action_menu, menu);
//mode.setTitle("Select Items");
mode.setTitle("1 item selected");
return true;
}

public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.delete:
SparseBooleanArray checked = gridView.getCheckedItemPositions();
try {
int len = checked.size();
for (int i = 0; i < len; i++) {
if (checked.valueAt(i)) {
Integer position = checked.keyAt(i);
//deleteToMessageHistory(position);
}
}
}catch (Exception i){
Toast.makeText(PhotosGridViewActivity.this, "Message was not deleted. Try again.", Toast.LENGTH_SHORT).show();
}
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
int selectCount = gridView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setTitle("1 item selected");
break;
default:
mode.setTitle("" + selectCount + " items selected");
break;
}
}
}

感谢您的帮助!

==UPDATE==

这是 MainActivity 代码:

public class PhotosGridViewActivity extends Activity {

private PhotosUtils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private PhotosGridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Initilizing Grid View
InitilizeGridLayout();

}

private void InitilizeGridLayout() {
setContentView(R.layout.photos_grid_view);
utils = new PhotosUtils(PhotosGridViewActivity.this);
gridView = (GridView) findViewById(R.id.grid_view);
// loading all image paths from SD card
imagePaths = utils.getFilePaths();
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());

columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);

gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);

gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
gridView.setMultiChoiceModeListener(new MultiChoiceModeListener());

// Gridview adapter
adapter = new PhotosGridViewImageAdapter(PhotosGridViewActivity.this, imagePaths,
columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
gridView.getItemAtPosition(position);
Intent i = new Intent(PhotosGridViewActivity.this, PhotosScreenViewActivity.class);
i.putExtra("position", position);
PhotosGridViewActivity.this.startActivity(i);
}
});
}

public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action_menu, menu);
//mode.setTitle("Select Items");
mode.setTitle("1 item selected");
return true;
}

public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.delete:
SparseBooleanArray checked = gridView.getCheckedItemPositions();
try {
int len = checked.size();
for (int i = 0; i < len; i++) {
if (checked.valueAt(i)) {
Integer position = checked.keyAt(i);
//deleteToMessageHistory(position);
}
}
}catch (Exception i){
Toast.makeText(PhotosGridViewActivity.this, "Message was not deleted. Try again.", Toast.LENGTH_SHORT).show();
}
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
int selectCount = gridView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setTitle("1 item selected");
break;
default:
mode.setTitle("" + selectCount + " items selected");
break;
}
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(co.glurl.appoid.R.menu.photo_gallery, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
/** Go to the user's add photos. */
startActivity(new Intent(this, PhotoIntentActivity.class));
break;
//case R.id.settings:
/** Go to the user's settings photos. */
// startActivity(new Intent(this, PhotoGridSettings.class));
// break;
default:
return super.onContextItemSelected(item);
}
return true;
}

}

最佳答案

我的解决方案。感谢@pushbit 指导我完成它。

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = (ImageView) convertView;
if (imageView == null) {
imageView = new ImageView(_activity);
}

// Trigger the download of the URL asynchronously into the image view.
if(_filePaths.get(position).contains(".jpg")) {
Picasso.with(_activity)
.load(new File(_filePaths.get(position)))
.resize(imageWidth, imageWidth)
.centerCrop()
.tag(_activity)
.into(imageView);
}else if(_filePaths.get(position).contains(".mp4")){
VideoRequestHandler videoRequestHandler;
Picasso picassoInstance;
videoRequestHandler=new VideoRequestHandler();
picassoInstance = new Picasso.Builder(_activity.getApplicationContext())
.addRequestHandler(videoRequestHandler)
.build();
picassoInstance
.load(videoRequestHandler.SCHEME_VIDEO+":"+_filePaths.get(position))
.resize(imageWidth, imageWidth)
.centerCrop()
.tag(_activity)
.into(imageView);
}
return imageView;
}

public static boolean deleteToPhotoAlbum(Integer position) {
File file = new File(_filePaths.get(position));
boolean deleted = file.delete();
return deleted;
}

public class VideoRequestHandler extends RequestHandler {
public String SCHEME_VIDEO = "video";
@Override
public boolean canHandleRequest(Request data)
{
String scheme = data.uri.getScheme();
return (SCHEME_VIDEO.equals(scheme));
}

@Override
public Result load(Request data, int arg1) throws IOException
{
Bitmap bm = ThumbnailUtils.createVideoThumbnail(data.uri.getPath(), MediaStore.Images.Thumbnails.MINI_KIND);
return new Result(bm, Picasso.LoadedFrom.DISK);
}
}

关于java - 通过单击异步 gridview 中的图像来防止在访问上下文操作菜单时重新加载 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29997215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com