0

我正在开发一个 android 应用程序,我想在一个片段中显示所有画廊图像。我已经让片段与其中的所有画廊图像一起作为缩略图使用。然后我想以马赛克格式显示所有图像,但找不到任何相关信息。所以我决定使用 AndroidStaggeredGrid 库以 ETsy 风格显示图像。我已经成功导入了库,我根据AndroidStaggeredGrid的github页面对代码做了一些修改。但图像仍以与普通画廊和列相同的格式显示。有人可以帮我吗。下面是代码。

适配器 - 这是我的图像视图的适配器。在这里我添加了背景颜色只是为了测试它是否工作正常。但它不是。

package com.ultimate.camera.adapters;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;

import com.etsy.android.grid.util.DynamicHeightImageView;
import com.ultimate.camera.R;
import com.ultimate.camera.adapters.items.PhotoItem;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class PhotoAdapter extends ArrayAdapter<PhotoItem>{
private static final String TAG = "PhotoAdaptor";
    private Context context;
    private int resourceId;
    private final Random mRandom;
    private final ArrayList<Integer> mBackgroundColors;

    private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();

    public PhotoAdapter(Context context, int resourceId,
                                 List<PhotoItem> items, boolean useList) {
        super(context, resourceId, items);
        mRandom = new Random();
        this.context = context;
        this.resourceId = resourceId;
        mBackgroundColors = new ArrayList<Integer>();
        mBackgroundColors.add(R.color.orange);
        mBackgroundColors.add(R.color.green);
        mBackgroundColors.add(R.color.blue);
        mBackgroundColors.add(R.color.yellow);
        mBackgroundColors.add(R.color.grey);
    }
 private class ViewHolder {
        DynamicHeightImageView photoImageView;
    }

    /**
     * Populate the view holder with data.
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        PhotoItem photoItem = getItem(position);
        View viewToUse = null;

 LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            holder = new ViewHolder();
            viewToUse = mInflater.inflate(resourceId, null);
            holder.photoImageView = (DynamicHeightImageView) viewToUse.findViewById(R.id.imageView);
            viewToUse.setTag(holder);
        } else {
            viewToUse = convertView;
            holder = (ViewHolder) viewToUse.getTag();
        }

        double positionHeight = getPositionRatio(position);
        int backgroundIndex = position >= mBackgroundColors.size() ?
                position % mBackgroundColors.size() : position;
        Log.d(TAG, "getView position:" + position + " h:" + positionHeight);

        // Set the thumbnail

        holder.photoImageView.setImageURI(photoItem.getThumbnailUri());
        holder.photoImageView.setHeightRatio(positionHeight);

        viewToUse.setBackgroundResource(mBackgroundColors.get(backgroundIndex));

        return viewToUse;
    }

    private double getPositionRatio(final int position) {
        double ratio = sPositionHeightRatios.get(position, 0.0);

if (ratio == 0) {
            ratio = getRandomHeightRatio();
            sPositionHeightRatios.append(position, ratio);
            Log.d(TAG, "getPositionRatio:" + position + " ratio:" + ratio);
        }
        return ratio;
    }

    private double getRandomHeightRatio() {
        return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5 the width
    }
}

PhotoItem java 这个接口是获取适配器的photoItem

package com.ultimate.camera.adapters.items;

import android.net.Uri;
public class PhotoItem {
private Uri thumbnailUri;
    private Uri fullImageUri;

    public PhotoItem(Uri thumbnailUri,Uri fullImageUri) {
        this.thumbnailUri = thumbnailUri;
        this.fullImageUri = fullImageUri;
    }

    /**
     * Getters and setters
     */
    public Uri getThumbnailUri() {
        return thumbnailUri;
    }

    public void setThumbnailUri(Uri thumbnailUri) {
        this.thumbnailUri = thumbnailUri;
    }

    public Uri getFullImageUri() {
        return fullImageUri;
    }

    public void setFullImageUri(Uri fullImageUri) {
        this.fullImageUri = fullImageUri;
    }
}

用于照片库的 PhotoGalleryFragment XML 布局

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <!--<FrameLayout-->

        <!--android:layout_width="fill_parent"-->
        <!--android:layout_height="fill_parent">-->
        <!--<GridView-->
            <!--style="@style/GridView.PhotoGallery"-->
            <!--android:id="@android:id/list"-->
            <!--android:numColumns="3" />-->

        <com.etsy.android.grid.StaggeredGridView
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@android:id/list"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            app:item_margin="8dp"
            app:column_count="2"


            ></com.etsy.android.grid.StaggeredGridView>
        <TextView
            android:id="@+id/empty"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:visibility="invisible"/>
    <!--</FrameLayout>-->
</LinearLayout>

照片项 XML

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <FrameLayout
        android:layout_width="@dimen/photo_width"
        android:layout_height="@dimen/photo_height">


        <com.etsy.android.grid.util.DynamicHeightImageView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/imageView"
            android:adjustViewBounds="false"
            android:gravity="center"
            android:scaleType="centerCrop"/>
    </FrameLayout>
</RelativeLayout>

PhotoGalleryFragment.Java

package com.ultimate.camera.fragments;

import android.app.Activity;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Loader;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.etsy.android.grid.StaggeredGridView;
import com.ultimate.camera.R;
import com.ultimate.camera.activities.MainActivity;
import com.ultimate.camera.adapters.PhotoAdapter;
import com.ultimate.camera.adapters.items.PhotoItem;
import com.ultimate.camera.utilities.PhotoGalleryAsyncLoader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SimplePhotoGalleryListFragment extends BaseFragment implements AbsListView.OnItemClickListener,
        LoaderManager.LoaderCallbacks<List<PhotoItem>>  {
protected OnFragmentInteractionListener mListener;
   // protected AbsListView mListView;
    protected PhotoAdapter mAdapter;
    protected ArrayList<PhotoItem> mPhotoListItem;
    protected TextView mEmptyTextView;
    protected ProgressDialog mLoadingProgressDialog;
    protected StaggeredGridView mListView;

    /**
     * Required empty constructor
     */
    public SimplePhotoGalleryListFragment() {
        super();
    }

    /**
     * Static factory method
     * @param sectionNumber
     * @return
     */
    public static SimplePhotoGalleryListFragment newInstance(int sectionNumber) {
        SimplePhotoGalleryListFragment fragment = new SimplePhotoGalleryListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

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

        // Create an empty loader and pre-initialize the photo list items as an empty list.
        Context context = getActivity().getBaseContext();

        // Set up empty mAdapter
        mPhotoListItem = new ArrayList<PhotoItem>() ;
        mAdapter = new PhotoAdapter(context,
                R.layout.photo_item,
                mPhotoListItem, false);

        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(0, null, this);
    }

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


    }

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

        // Set the mAdapter
        mListView = (StaggeredGridView) view.findViewById(android.R.id.list);
        ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
        mEmptyTextView = (TextView)view.findViewById(R.id.empty);

        // Show the empty text / message.
        resolveEmptyText();

        // Set OnItemClickListener so we can be notified on item clicks
        mListView.setOnItemClickListener(this);

        return view;
    }
protected void resolveEmptyText(){
        if(mAdapter.isEmpty()){
            mEmptyTextView.setVisibility(View.VISIBLE);
            setEmptyText();
        } else {
            mEmptyTextView.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
            // Show a progress dialog.
            mLoadingProgressDialog = new ProgressDialog(getActivity());
            mLoadingProgressDialog.setMessage("Loading Photos...");
            mLoadingProgressDialog.setCancelable(true);
            mLoadingProgressDialog.show();
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        cancelProgressDialog();
    }

    @Override
    public void onPause(){
        super.onPause();
        cancelProgressDialog();
    }

    @Override
    public void onStop(){
        super.onStop();
        cancelProgressDialog();
    }

    /**
     * This is only triggered when the user selects a single photo.
     * @param parent
     * @param view
     * @param position
     * @param id
     */

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (null != mListener) {
            // Tell the share builder to add the photo to the share operation.
            PhotoItem photoListItem = (PhotoItem)this.mAdapter.getItem(position);
            String imagePath = photoListItem.getThumbnailUri().getPath();
            mListener.onFragmentInteraction(MainActivity.SELECT_PHOTO_ACTION);
            resetFragmentState();
        }
    }

    /**
     * Used when hitting the back button to reset the mFragment UI state
     */
    protected void resetFragmentState(){
        // Clear view state
        getActivity().invalidateOptionsMenu();
        ((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged();
    }
public void setEmptyText() {
        mEmptyTextView.setText("No Photos!");
    }

    /**
     * Loader Handlers for loading the photos in the background.
     */
    @Override
    public Loader<List<PhotoItem>> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.  This
        // sample only has one Loader with no arguments, so it is simple.
        return new PhotoGalleryAsyncLoader(getActivity());
    }

    @Override
    public void onLoadFinished(Loader<List<PhotoItem>> loader, List<PhotoItem> data) {
        // Set the new data in the mAdapter.
        mPhotoListItem.clear();

        for(int i = 0; i < data.size();i++){
            PhotoItem item = data.get(i);
            mPhotoListItem.add(item);
        }

        mAdapter.notifyDataSetChanged();
        resolveEmptyText();
        cancelProgressDialog();
    }

    @Override
    public void onLoaderReset(Loader<List<PhotoItem>> loader) {
        // Clear the data in the mAdapter.
        mPhotoListItem.clear();
        mAdapter.notifyDataSetChanged();
        resolveEmptyText();
        cancelProgressDialog();
    }

    /**
     * Save cancel for the progress loader
     */
    private void cancelProgressDialog(){
        if(mLoadingProgressDialog != null){
            if(mLoadingProgressDialog.isShowing()){
                mLoadingProgressDialog.cancel();
            }
        }
    }
}

我的输出 我的输出格式

预期格式

您可以在我的输出图像中看到相同大小的缩略图,但我没有文字。但我希望所有图像都是不同大小的缩略图。

如果有人帮助我,我真的很感激。另外,如果有人知道如何创建图像的马赛克格式,我也给出了马赛克格式图像马赛克格式

4

2 回答 2

2

又挠了几下头,终于找到了答案。问题出在 PhotoItem 布局文件 (PhotoItem.XML) 中,我为每个将显示在片段中的 photoItem 定义了布局。有一个 FrameLayout 作为 DynamicImageView 部分的父级,它有自己的宽度和高度,因此不允许将动态高度 holder.photoImageView.setHeightRation(positionHeight) 设置为 PhotoItem。所以,唯一的变化是 PhotoItem.XML,我必须保持其余代码不变。

所以我不得不删除 FrameLayout 部分,只保留 DynamicImageView 作为 PhotoItem 布局。

照片项.XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

        <com.etsy.android.grid.util.DynamicHeightImageView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/imageView"
            android:adjustViewBounds="false"
            android:gravity="center"
            android:scaleType="centerCrop"/>

</RelativeLayout>

然后它工作正常,现在完成了,我附上了下面的截图:)

我仍然会寻找马赛克视图解决方案

谢谢

最终输出(预期)

于 2014-08-05T11:43:53.837 回答
0

由于 holder.photoImageView.setHeightRatio(positionHeight); 你得到了相同大小的所有图像 您为图像设置了 heightRatio,因此请删除此行及其所有效果..尝试删除 holder.photoImageView.setHeightRatio(positionHeight);

于 2014-08-02T06:47:02.900 回答