删除未在图库中重新映射的图像

时间:2016-05-05 12:12:09

标签: android android-fragments imageview android-imageview android-glide

我有一个基本导航抽屉活动,它会加载一个片段。片段的布局中有RecyclerView。 RecyclerView有一个适配器,它使用Glide从我的本地文件夹加载图像。我有一个detailView活动来显示全屏图像。在全屏视图中,我有一个菜单选项来删除当前图像。我的逻辑在物理上删除了文件,但删除没有反映在库中(我的意思是,图像仍会显示,直到我导航到另一个活动并返回。

BaseActivity.java

public class BaseActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    protected RelativeLayout relativeLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        relativeLayout = (RelativeLayout) findViewById(R.id.content_frame);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        Fragment item1Fragment = new Item1Fragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.content_frame, item1Fragment, null);
        fragmentTransaction.commit();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.base, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
        if (id == R.id.nav_camera) {
            Fragment item1Fragment = new Item1Fragment();
            fragmentTransaction.replace(R.id.content_frame, item1Fragment);
            fragmentTransaction.commit();
        } else if (id == R.id.nav_gallery) {
            Fragment item2Fragment = new Item2Fragment();
            fragmentTransaction.replace(R.id.content_frame, item2Fragment);
            fragmentTransaction.commit();
        } else if (id == R.id.nav_slideshow) {
            Toast.makeText(getApplicationContext(), "333", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_manage) {
            Toast.makeText(getApplicationContext(), "444", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_share) {
            Toast.makeText(getApplicationContext(), "555", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_send) {
            Toast.makeText(getApplicationContext(), "666", Toast.LENGTH_SHORT).show();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

基本活动布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_base"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <RelativeLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_base"
        app:menu="@menu/activity_base_drawer" />

</android.support.v4.widget.DrawerLayout>

片段

public class Item1Fragment extends Fragment {
    String absPath = "storage/sdcard/DCIM/Camera";
    File targetDir = new File(absPath);
    android.view.ActionMode actionMode;
    private ArrayList<ImageModel> data = new ArrayList<>();
    private GalleryAdapter mAdapter;
    private RecyclerView mRecyclerView;
    private Map<String, String> contactNameMap = new HashMap<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        List<File> fileList = getAllFiles(targetDir);
        for (int i = 0; i < fileList.size(); i++) {

            ImageModel imageModel = new ImageModel();
            imageModel.setName(fileList.get(i).getName());
            try {
                imageModel.setUrl(fileList.get(i).toURI().toURL().toString());
            } catch (MalformedURLException e) {
                Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            }
            data.add(imageModel);
        }
        View view = inflater.inflate(R.layout.fragment_item1, container, false);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.list1);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        } else {
            mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        }

        mRecyclerView.setHasFixedSize(true);
        mAdapter = new GalleryAdapter(getActivity(), data);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(),
                new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Intent intent = new Intent(getActivity(), DetailActivity.class);
                        intent.putParcelableArrayListExtra("data", data);
                        intent.putExtra("pos", position);
                        intent.putExtra("origin", "Item1Fragment");
                        intent.putExtra("url", absPath);
                        startActivity(intent);
                    }
                }));
        return view;
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private boolean IsSupportedFile(String filePath) {
        String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
                filePath.length());

        if (Arrays.asList("jpg", "jpeg",
                "png")
                .contains(ext.toLowerCase(Locale.getDefault())))
            return true;
        else
            return false;

    }

    public ArrayList<File> getAllFiles(File directory) {
        ArrayList<File> filePaths = new ArrayList<File>();
        if (directory.isDirectory()) {
            File[] listFiles = directory.listFiles();
            if (listFiles.length > 0) {
                for (int i = 0; i < listFiles.length; i++) {
                    String filePath = listFiles[i].getAbsolutePath();
                    if (IsSupportedFile(filePath)) {
                        filePaths.add(listFiles[i]);
                    }
                }
            } else {
                Toast.makeText(
                        getActivity(),
                        "Album is empty. Please load some images in it !",
                        Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(
                    getActivity(),
                    " directory path is not valid! Please set the image directory name AppConstant.java class",
                    Toast.LENGTH_LONG).show();
        }
        return filePaths;
    }
}

片段布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.akl.nav2.Item1Fragment">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list1" android:background="#FFBB00"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</RelativeLayout>

GalleryAdapter

public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private List<ImageModel> data = new ArrayList<>();
    private SparseBooleanArray selectedItems;

    public GalleryAdapter(Context context, List<ImageModel> data) {
        this.context = context;
        this.data = data;
        selectedItems = new SparseBooleanArray();
    }

    public void addData(ImageModel newModelData, int position) {
        data.add(position, newModelData);
        notifyItemInserted(position);
    }

    public void removeData(int position) {
        data.remove(position);
        notifyItemRemoved(position);
    }

    public void toggleSelection(int pos) {
        if (selectedItems.get(pos, false)) {
            selectedItems.delete(pos);
        } else {
            selectedItems.put(pos, true);
        }
        notifyItemChanged(pos);
    }

    public void clearSelections() {
        selectedItems.clear();
        notifyDataSetChanged();
    }

    public int getSelectedItemCount() {
        return selectedItems.size();
    }

    public List<Integer> getSelectedItems() {
        List<Integer> items = new ArrayList<Integer>(selectedItems.size());
        for (int i = 0; i < selectedItems.size(); i++) {
            items.add(selectedItems.keyAt(i));
        }
        return items;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder;
        View v;
        v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.list_item, parent, false);
        viewHolder = new MyItemHolder(v);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        holder.itemView.setActivated(selectedItems.get(position, false));
        Glide.with(context).load(data.get(position).getUrl())
                .thumbnail(0.5f)
                .override(200, 200)
                .crossFade()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(((MyItemHolder) holder).mImg);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public static class MyItemHolder extends RecyclerView.ViewHolder {
        ImageView mImg;

        public MyItemHolder(View itemView) {
            super(itemView);
            mImg = (ImageView) itemView.findViewById(R.id.item_img);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

Glide会针对每个网址创建一个副本,因此您需要使用给定的网址创建一个File对象,并检查文件是否存在。

onBindViewHolder中的更改:

File file = new File(data.get(position).getUrl());
if(file.exists()) {
    Glide.with(context).load(data.get(position).getUrl())
    .thumbnail(0.5f)
    .override(200, 200)
    .crossFade()
    .skipMemoryCache(true)
    .diskCacheStrategy(DiskCacheStrategy.NONE)
    .into(((MyItemHolder) holder).mImg);
} else {
  //File doesn't exist
}