我正在使用ViewPager和Action Bar。在操作栏上有一些组件,例如删除按钮。我的应用程序是一个图库应用程序,我想删除所选的图片。它有效,但我不知道如何刷新我的片段以便从gridview中删除已删除的图片。
我试着做了很长时间,这对我来说非常重要。
感谢您的帮助。
MainActivity:
public class MainActivity extends FragmentActivity {
private static final int FOLDER = 0;
private static final int TEXT_ID = 0;
private static final String PATH_OF_FILES = "/Pictures/";
File folder;
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
ArrayList<ImageItem> listOfFiles = new ArrayList<ImageItem>();
private String dirToMove = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listOfFiles = FileListerUtil.getFilesFromDirectory(PATH_OF_FILES);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager) findViewById(R.id.pager);
Tab.setAdapter(TabAdapter);
Tab.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position);
}
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
@Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
}
};
actionBar.addTab(actionBar.newTab().setText("Pic")
.setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Other")
.setTabListener(tabListener));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.activity_main_action, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_remove:
for (int i = 0; i < listOfFiles.size(); i++) {
if (listOfFiles.get(i).isChecked()) {
File file = new File(listOfFiles.get(i).getImagePath());
file.delete();
}
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public ArrayList<ImageItem> getListOfFiles() {
return listOfFiles;
}
public void setListOfFiles(ArrayList<ImageItem> listOfFiles) {
this.listOfFiles = listOfFiles;
}
public String getDirToMove() {
return dirToMove;
}
public void setDirToMove(String dirToMove) {
this.dirToMove = dirToMove;
}
public static boolean copyFile(String from, String to) {
try {
File sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
int end = from.toString().lastIndexOf("/");
String str1 = from.toString().substring(0, end);
String str2 = from.toString().substring(end+1, from.length());
File source = new File(str1, str2);
File destination= new File(to, str2);
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
return true;
} catch (Exception e) {
return false;
}
}
FragmentStateAdapter:
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new Pictures();
case 1:
return new Albums();
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 2; //No of Tabs
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
图片:
public class Pictures extends Fragment{
private LruCache<String, Bitmap> mMemoryCache;
private int count;
private Bitmap[] thumbnails;
private String[] arrPath;
private Context context;
ArrayList<ImageItem> fileListParam = new ArrayList<ImageItem>();
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.layout.fragment_menu, menu);
}
public class ImageAdapter extends BaseAdapter {
boolean[] checkState;
private LayoutInflater inflat;
private Context mContext;
ArrayList<ImageItem> itemList = new ArrayList<ImageItem>();
public ImageAdapter(ArrayList<ImageItem> files, Context c) {
mContext = c;
inflat = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
this.itemList = files;
}
void clear() {
itemList.clear();
}
void remove(int index) {
itemList.remove(index);
}
@Override
public int getCount() {
return itemList.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View rowView = convertView;
// reuse views
if (rowView == null) {
rowView = inflat.inflate(R.layout.galleryitem, null);
// configure view holder
final ViewHolderPictures viewHolderPictures = new ViewHolderPictures();
viewHolderPictures.imageview = (ImageView) rowView
.findViewById(R.id.thumbImage);
viewHolderPictures.checkbox = (CheckBox) rowView
.findViewById(R.id.itemCheckBox);
viewHolderPictures.imageview.setBackgroundResource(R.drawable.image_border);
viewHolderPictures.imageview.setScaleType(ImageView.ScaleType.FIT_XY);
viewHolderPictures.imageview.setPadding(5, 5, 5, 5);
rowView.setTag(viewHolderPictures);
}
// fill data
ViewHolderPictures holder = (ViewHolderPictures) rowView.getTag();
holder.checkbox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0,
boolean arg1) {
itemList.get(position).setChecked(arg1);
}
});
final Bitmap bm = getBitmapFromMemCache(itemList.get(position)
.getImagePath());
if (bm == null) {
BitmapWorkerTask task = new BitmapWorkerTask(holder.imageview);
task.execute(itemList.get(position).getImagePath());
}
holder.imageview.setImageBitmap(bm);
holder.checkbox.setChecked(itemList.get(position).isChecked());
return rowView;
}
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth,
int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
public class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage
// collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
protected Bitmap doInBackground(String... params) {
final Bitmap bitmap = decodeSampledBitmapFromUri(params[0], 140,
120);
addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = (ImageView) imageViewReference
.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
int fragVal;
ImageAdapter myImageAdapter;
static Pictures init(int val) {
Pictures truitonFrag = new Pictures();
// Supply val input as an argument.
Bundle args = new Bundle();
args.putInt("val", val);
truitonFrag.setArguments(args);
return truitonFrag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
setHasOptionsMenu(true);
final int memClass = ((ActivityManager) getActivity().getSystemService(
Context.ACTIVITY_SERVICE)).getMemoryClass();
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = 1024 * 1024 * memClass / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in bytes rather than number
// of items.
return bitmap.getByteCount();
}
};
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Gridview gridview;
View layoutView = inflater.inflate(R.layout.kepgrid, container, false);
gridview = (GridView) layoutView.findViewById(R.id.gv_photolist);
ArrayList<ImageItem> files = ((MainActivity) getActivity())
.getListOfFiles();
context = getActivity();
myImageAdapter = new ImageAdapter(files, context);
gridview.setAdapter(myImageAdapter);
return layoutView;
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return (Bitmap) mMemoryCache.get(key);
}
}