从自定义库中获取文件名

时间:2016-03-05 13:22:59

标签: android listview filenames image-gallery

我有这个自定义适配器适用于图库在列表视图中显示图像

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CustomPhotoActivity extends Activity {

    private GridView grdImages;
    private Button btnSelect;

    private ImageAdapter imageAdapter;
    private String[] arrPath;
    private boolean[] thumbnailsselection;
    private int ids[];
    private int count;
    private ListView lv;
    private Cursor cursor;
    /**
     * Overrides methods
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_gallery);
        //grdImages= (GridView) findViewById(R.id.grdImages);
        btnSelect= (Button) findViewById(R.id.btnSelect);
        lv= (ListView) findViewById(R.id.imglist);
        final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
        final String orderBy = MediaStore.Images.Media._ID;
        @SuppressWarnings("deprecation")
        Cursor imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
        int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
        this.count = imagecursor.getCount();
        this.arrPath = new String[this.count];
        ids = new int[count];
        this.thumbnailsselection = new boolean[this.count];
        for (int i = 0; i < this.count; i++) {
            imagecursor.moveToPosition(i);
            ids[i] = imagecursor.getInt(image_column_index);
            int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
            arrPath[i] = imagecursor.getString(dataColumnIndex);
        }

        imageAdapter = new ImageAdapter();
        //grdImages.setAdapter(imageAdapter);
        lv.setAdapter(imageAdapter);
        imagecursor.close();


        btnSelect.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                final int len = thumbnailsselection.length;
                int cnt = 0;
                String selectImages = "";
                for (int i = 0; i < len; i++) {
                    if (thumbnailsselection[i]) {
                        cnt++;
                        selectImages = selectImages + arrPath[i] + "|";
                    }
                }
                if (cnt == 0) {
                    Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show();
                } else {

                    Log.d("SelectedImages", selectImages);
                    Intent i = new Intent();
                    i.putExtra("data", selectImages);
                    setResult(Activity.RESULT_OK, i);
                    finish();
                }
            }
        });
    }
    @Override
    public void onBackPressed() {
        setResult(Activity.RESULT_CANCELED);
        super.onBackPressed();

    }

    /**
     * Class method
     */

    /**
     * This method used to set bitmap.
     * @param iv represented ImageView
     * @param id represented id
     */

    private void setBitmap(final ImageView iv, final int id) {

        new AsyncTask<Void, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Void... params) {
                return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);
                iv.setImageBitmap(result);
            }
        }.execute();
    }

    private void setText(final TextView iv, final int id) {

        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... params) {

            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                iv.setText(result);
            }
        }.execute();
    }
    /**
     * List adapter
     * @author tasol
     */

    public class ImageAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public ImageAdapter() {
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

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

        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.custom_gallery_item, null);
                holder.imgThumb = (ImageView) convertView.findViewById(R.id.imgThumb);
                holder.chkImage = (CheckBox) convertView.findViewById(R.id.chkImage);
                holder.listtext = (TextView) convertView.findViewById(R.id.listtext);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.chkImage.setId(position);
            holder.imgThumb.setId(position);
            holder.listtext.setId(position);
            holder.chkImage.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    if (thumbnailsselection[id]) {
                        cb.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        cb.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });
            holder.imgThumb.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    int id = holder.chkImage.getId();
                    if (thumbnailsselection[id]) {
                        holder.chkImage.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        holder.chkImage.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });
            try {
                setBitmap(holder.imgThumb, ids[position]);
            } catch (Throwable e) {
            }
            holder.chkImage.setChecked(thumbnailsselection[position]);
            holder.id = position;
            return convertView;
        }
    }


    /**
     * Inner class
     * @author tasol
     */
    class ViewHolder {
        ImageView imgThumb;
        TextView listtext;
        CheckBox chkImage;
        int id;
    }

}

在这里我有一个setText Async函数,我需要返回文件名并将其显示在listview中的图像旁边。

 private void setText(final TextView iv, final int id) {

        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... params) {

            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                iv.setText(result);
            }
        }.execute();
    }

任何人都可以告诉我如何返回文件名并将其分配给我的textview?

1 个答案:

答案 0 :(得分:0)

int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
int bucket_display_name_index = imagecursor.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
String[] fileNames = new String[count];
String[] bucketDisplayNames = new String[count];
for (int i = 0; i < this.count; i++) {
        imagecursor.moveToPosition(i);
        ids[i] = imagecursor.getInt(image_column_index);
        // Bucket display names, don't know how these strings look, but try 
        // this if for nothing else than atleast for knowledge
        bucketDisplayNames[i] = imagecursor.getString(bucket_display_name_index);

        int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        arrPath[i] = imagecursor.getString(dataColumnIndex);

        // This will be the fileName of the image.
        filesNames[i] = getFileName(arrPath[i]);
    }

您可以使用此列索引获取存储桶显示名称

int bucket_display_name_index = imagecursor.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME);

或使用它来获取文件本身的路径,从中可以提取文件名。

int image_path_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);

从你的代码我可以看到你确实正在将文件的路径提取到 变量arrPath,这是你如何从路径中提取文件名(别忘了添加它 对你的班级有用!)

public String getFileName(String path) {
    separatorChar = System.getProperty("file.separator", "/").charAt(0);
    separator = String.valueOf(separatorChar);
    int separatorIndex = path.lastIndexOf(separator);
    return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
}

您可以使用包含显示名称的bucketDisplayNames数组,(我不知道这些字符串的外观)或者您可以使用fileNames数组。