我是靠谱客的博主 糟糕曲奇,最近开发中收集的这篇文章主要介绍Android图片和视频简单选择器,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在实际的应用过程中图片和视频的显示使用异步加载

一、点击title时切换图片和视频

1、修改AndroidManifest.xml文件,使用自定义主题

 	<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/customTheme">
        <activity
            android:name="com.example.imageselector.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


2、在onCreate方法中添加

	requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

	setContentView(R.layout.activity_main);

	// Set the header.
	getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
	R.layout.action_bar);


3、写布局文件

4、Photo和Video的点击事件,点击时切换fragment,调用switchFragment方法

	private void initFragment() {

		this.photoPickerFragment = new PhotoAndVideoPickerFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("fragmentIndex", 0);
		this.photoPickerFragment.setArguments(bundle);

		this.videoPickerFragment = new PhotoAndVideoPickerFragment();
		Bundle videoBundle = new Bundle();
		videoBundle.putInt("fragmentIndex", 1);
		this.videoPickerFragment.setArguments(videoBundle);

		switchFragment(photoPickerFragment);
		this.currentFragment = this.photoPickerFragment;
	}

	private void switchFragment(PhotoAndVideoPickerFragment newFragment) {
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		if (null == this.currentFragment) {
			transaction.add(R.id.picker_fragment_container, newFragment)
					.commit();
		} else {
			if (currentFragment != newFragment) {
				if (!newFragment.isAdded()) {
					transaction.hide(currentFragment)
							.add(R.id.picker_fragment_container, newFragment)
							.commit();
				} else {
					transaction.hide(currentFragment).show(newFragment)
							.commit();
				}
			}
		}
		
		this.currentFragment = newFragment;
	}


二、图片和视频选择页面

1、Photo和video 共用一个fragment类

设置一个boolean变量控制显示的数据是photo还是video

FolderListPopupWindow是自定义的popupwindow,用于显示所有包含photo/video的folder

public class PhotoAndVideoPickerFragment extends Fragment {

	protected Context context;

	protected GridView gridView;

	protected Button folderButton;

	protected List<Folder> folders = new ArrayList<Folder>();
	
	private List<Image> images = new ArrayList<Image>();

	protected FolderListPopupWindow popupWindow;

	protected FolderListPopupWindowAdapter folderAdapter;

	protected ImageAndVideoPickerAdapter adapter;
	
	private boolean isVideo;

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

		this.context = getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.image_video_picker, null);

		initView(view);

		return view;
	}

	public void initView(View view) {
		this.gridView = (GridView) view.findViewById(R.id.image_grid_view);
		this.folderButton = (Button) view.findViewById(R.id.folder_button);

		prepareBundle();
		getAllData();
		prepareFolders();
		setListenerForGridItem();
	}
	
	private void prepareBundle(){
		Bundle bundle = getArguments();
		if(null != bundle){
			int fragmentIndex = bundle.getInt("fragmentIndex");
			isVideo = fragmentIndex == 0 ? false : true;
		}
	}
	
	/**
	 * 获取所有的照片 准备folder list
	 * 
	 */
	public void getAllData() {
		folders.clear();
		images.clear();
		
		Uri uri = isVideo ? MediaStore.Video.Media.EXTERNAL_CONTENT_URI : MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		
		Cursor cursor = this.context.getContentResolver().query(
				uri, null, null, null,
				null);
		if (null != cursor) {
			while (cursor.moveToNext()) {
				String name = cursor.getString(cursor
						.getColumnIndex(Media.DISPLAY_NAME));
				String path = cursor.getString(cursor
						.getColumnIndex(Media.DATA));

				Image image = new Image();
				image.setName(name);
				image.setPath(path);
				this.images.add(image);

				organizeFileFromFolder(path, name, image);
			}
		}

		String folderName = isVideo ? "All Videos" : "All Images";
		// 将“all Images”放到folder list中
		Folder allFolder = new Folder();
		allFolder.setCover(images.get(0));
		allFolder.setName(folderName);
		allFolder.setImages(images);
		this.folders.add(0, allFolder);

		this.adapter = new ImageAndVideoPickerAdapter(this.context, images, isVideo);
		this.gridView.setAdapter(adapter);
		
		this.folderButton.setText(folderName);
	}

	/**
	 * 组织folder list
	 * 根据file path,将同一个path下的photo/video放到一个folder里面
	 * 
	 * @param filePath
	 * @param name
	 * @param image
	 */
	protected void organizeFileFromFolder(String filePath, String name,
			Image image) {
		File folderFile = new File(filePath).getParentFile();
		if (folderFile != null && folderFile.exists()) {
			String folderPath = folderFile.getAbsolutePath();
			Folder folder = getImageFolder(folderPath);

			if (null == folder) {
				// 将第一个图片作为folder的封面,放到image list中
				folder = new Folder();
				folder.setCover(image);
				folder.setName(folderFile.getName());
				folder.setPath(folderPath);

				List<Image> images = new ArrayList<Image>();
				images.add(image);
				folder.setImages(images);

				// 将folder放到folder list中
				folders.add(folder);
			} else {

				folder.getImages().add(image);
			}
		}
	}

	/**
	 * 获取folder,如果存在则不需要创建
	 * 
	 * @param folderPath
	 * @return
	 */
	public Folder getImageFolder(String folderPath) {
		if ((null != folders) && !TextUtils.isEmpty(folderPath)) {
			for (Folder folder : folders) {
				if (folderPath.equals(folder.getPath())) {
					return folder;
				}
			}
		}

		return null;
	}

	/**
	 * folder button点击事件
	 * 
	 */
	public void prepareFolders() {
		this.folderButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				showPopupWindow();
			}
		});
	}

	/**
	 * 点击folder button时弹出folder list
	 * 
	 */
	public void showPopupWindow() {
		if (null == this.popupWindow) {
			this.popupWindow = new FolderListPopupWindow(this.context);
			this.folderAdapter = new FolderListPopupWindowAdapter(this.context,
					folders);
			this.popupWindow.setAdapter(folderAdapter);
		}
		this.popupWindow.showPopupWindow();

		this.popupWindow.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view,
					int position, long id) {
				folderAdapter.setSelectedPosition(position);
				popupWindow.dismiss();

				Folder folder = (Folder) folderAdapter.getItem(position);
				folderButton.setText(folder.getName());
				setData(folder);
			}
		});
	}

	/**
	 * 点击单独的photo/video时的响应事件,选中/未选中
	 * 
	 */
	public void setListenerForGridItem() {
		this.gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view,
					int position, long id) {

				Image image = PhotoAndVideoPickerFragment.this.adapter.getImages()
						.get(position);
				PhotoAndVideoPickerFragment.this.adapter.setSelectedImage(image);
			}
		});
	}

	/**
	 * 处理不同的folder中的数据,当点击单独的folder时调用
	 * 
	 * @param folder
	 */
	public void setData(Folder folder) {
		this.adapter.setImages(folder.getImages());
	}
}

2、photo和video adapter

需要引入picasso-2.5.2.jar来显示photo

使用ThumbnailUtils.createVideoThumbnail来获取视频缩略图

public class ImageAndVideoPickerAdapter extends BaseAdapter {

	private Context context;

	private List<Image> images = new ArrayList<Image>();

	private ViewHolder holder;

	private final int mGridWidth;

	private List<Image> selectedImages = new ArrayList<Image>();

	private boolean isVideo;

	public ImageAndVideoPickerAdapter(Context context, List<Image> images,
			boolean isVideo) {
		this.context = context;
		this.images = images;
		this.isVideo = isVideo;

		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		int width = wm.getDefaultDisplay().getWidth();
		mGridWidth = width / 3;
	}

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

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

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

	@Override
	public View getView(int position, View view, ViewGroup parent) {
		if (view == null) {
			holder = new ViewHolder();
			view = LayoutInflater.from(this.context).inflate(
					R.layout.image_video_item, parent, false);
			holder.imageView = (ImageView) view.findViewById(R.id.item_view);
			holder.checkMark = (ImageView) view.findViewById(R.id.check_mark);
			holder.videoMark = (ImageView) view
					.findViewById(R.id.video_play_button);
			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}

		if (holder != null) {
			Image image = images.get(position);

			File imageFile = new File(image.getPath());
			if (imageFile.exists()) {
				if (this.isVideo) {
					Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(image.getPath(),
					          MediaStore.Video.Thumbnails.MICRO_KIND);
					holder.imageView.setImageBitmap(ThumbnailUtils.extractThumbnail(bitmap, mGridWidth, mGridWidth));
					
				} else {
					// Show the image thumbnail
					Picasso.with(context).load(imageFile)
							.placeholder(R.drawable.default_error)
							.resize(mGridWidth, mGridWidth).centerCrop()
							.into(holder.imageView);
				}

			} else {
				holder.imageView.setImageResource(R.drawable.default_error);
			}

			if (this.selectedImages.contains(image)) {
				holder.checkMark.setImageResource(R.drawable.btn_selected);
			} else {
				holder.checkMark.setImageResource(R.drawable.btn_unselected);
			}

			if (this.isVideo) {
				holder.videoMark.setVisibility(View.VISIBLE);
			} else {
				holder.videoMark.setVisibility(View.GONE);
			}
		}
		return view;
	}

	public void setSelectedImage(Image image) {
		if (this.selectedImages.contains(image)) {
			this.selectedImages.remove(image);
		} else {
			this.selectedImages.add(image);
		}

		notifyDataSetChanged();
	}

	public void setImages(List<Image> images) {
		this.images = images;
		notifyDataSetChanged();
	}

	public List<Image> getImages() {
		return images;
	}

	private class ViewHolder {
		private ImageView imageView;

		private ImageView checkMark;

		private ImageView videoMark;
	}
}
效果图如下:



最后

以上就是糟糕曲奇为你收集整理的Android图片和视频简单选择器的全部内容,希望文章能够帮你解决Android图片和视频简单选择器所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部