GridView中的setOnItemLongClickListener不可单击

时间:2015-03-25 06:15:50

标签: android android-gridview onitemclicklistener onitemlongclicklistener

我已经尝试了我可以在SO上找到的所有建议,并且我能够在我的ListView上成功使用这个确切的代码,但出于某种原因,我无法设置长按一下监听器在我GridView上。我在方法setupGridViewListener();内登录,它甚至没有运行,但我在onCreateView()内有我的方法。不知道为什么它不会起作用。一旦长按,警报对话框就会弹出,但它没有。方法在我的班级底层。

更新

我没有提到我的onClickListener确实可以正常工作。所以我至少可以点击一下,这会显示我的活动。但是,那个代码在我的适配器中,所以也许它们应该在同一个类中?我将我的适配器和我的2 xml包括在内。

更新2 我发现了一些值得一提的东西,即使在我的代码再次运行之后也是如此。首先,将我的点击监听器放入我的适配器是一个错误。它让事情变得很慢......太多了,我很想找到一种方法来解决另一个问题。但最终,我不需要。我意识到我实际上可以将我的两个点击监听器都放到我的PhotoTab.java课程中。这立即使它更快(恢复正常)。但另一个奇怪的事情是,IDE不允许我使用OnClickListener,但我坚持要回到OnItemClickListener。所以,一旦我改变了这些,一切都恢复了。所以听众最终都在我的GridView变量上,例如gridView.setOnItemClickListener(new OnItemClickListener() {}不是我的ImageView项变量。也许这就是让事情变得更快的原因?有一个GridView,但有24个ImageView s(GridView个单元格)。但这只是猜测。我已将我的代码更新为当前正在运行的代码。除了我还在处理长按代码之外,所以还不行。但对话框警报仍然有效,GridView中的每个项目都是可点击的。

PhotoTab.java

    package org.azurespot.cutecollection.phototab;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;

import org.azurespot.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

/**
 * Created by mizu on 2/8/15.
 */
public class PhotoTab extends Fragment {

    private GridView gridView;
    File[] files;
    ArrayList<PhotoGridItem> photoList = new ArrayList<>();
    ArrayAdapter<PhotoGridItem> adapter;
    Bitmap bitmap;
    byte[] byteArray = null;
    private String[] allSDCardFiles = null;

    PhotoGridItem photoGridItem;

    public PhotoTab() {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.photo_tab, container, false);

        // with fragments, make sure you include the rootView when finding id
        gridView = (GridView) v.findViewById(R.id.photo_grid);

        // this null check won't instantiate again if it was already
//        if(adapter == null)
        adapter = new GridViewPhotoAdapter(getActivity(), R.layout.photo_grid_item);

        // Set the Adapter to GridView
        gridView.setAdapter(adapter);

        // load contents of SD card
        loadSDCard();

        // add the default icons remaining, to GridView, if less than 24 files on SD card
        for (int i = 0; i < (24 - allSDCardFiles.length); i++) {
            adapter.add(new PhotoGridItem(BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_photo_placeholder)));
            adapter.notifyDataSetChanged();
            i++;
        }

        //Convert the bitmap to byte array, so can pass through intent
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        final byte[] byteArray = stream.toByteArray();
        this.byteArray = byteArray;

        setupGridViewListener();

        return v;
    }


    public void loadSDCard() {

        try {
            // gets directory CutePhotos from sd card
            File cutePhotosDir = new File(Environment.getExternalStoragePublicDirectory
                    (Environment.DIRECTORY_PICTURES), "Cute Photos");
            // lists all files in CutePhotos, loads in Files[] array
            files = cutePhotosDir.listFiles();

            for (File singleFile : files) {

                String filePath = singleFile.getAbsolutePath();
                // this method makes size small for the view (to save memory)
                bitmap = decodeImageBitmap(filePath, 270, 270);
                photoGridItem = new PhotoGridItem(bitmap);
                // Check if this is a new bitmap file
                adapter.add(photoGridItem);
                adapter.notifyDataSetChanged();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        // get number of files in Cute Photos directory
        allSDCardFiles =  new String[files.length];

    }



    private void setupGridViewListener(){
        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapter,
                                    View item, int pos, long id) {

                Intent i = new Intent(getActivity(), PhotoViewerActivity.class);
                i.putExtra("photo", byteArray);
                startActivity(i);
            }

        });

        // to delete a photo item
        gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> aView, View item,
                                           final int pos, long id) {

                new AlertDialog.Builder(getActivity())
                        .setTitle("Delete")
                        .setMessage("Delete this cute photo?")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // delete from ArrayList first
//                                PhotoTab.photoList.remove(position);

                                // get file name then delete it from SD card
                                File cutePhotosDir = new File(Environment.getExternalStoragePublicDirectory
                                        (Environment.DIRECTORY_PICTURES), "CutePhotos/" + photoGridItem);
                                cutePhotosDir.delete();


                                // after each item delete, must refresh load so can delete again
//                                photoTab.loadSDCard();
                            }
                        })
                        .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                // do nothing
                                dialog.cancel();
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();

                return true;
            }
        });
    }

    // next 2 methods scale the bitmap image to a better size (so not huge)
    public static 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 static Bitmap decodeImageBitmap(String path, int reqWidth, int reqHeight) {


        // 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;
        Bitmap bm = BitmapFactory.decodeFile(path, options);

        return bm;
    }
}

GridViewPhotoAdapter

    package org.azurespot.cutecollection.phototab;

/**
* Created by mizu on 2/5/15.
*/
// package org.azurespot.cutecollection;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;

import org.azurespot.R;

/**
 * Created by mizu on 2/5/15.
 */
public class GridViewPhotoAdapter extends ArrayAdapter<PhotoGridItem> {

    public Context context;
    private int resourceId;
    ViewHolder holder = null;
    int position;

    public GridViewPhotoAdapter(Context context, int layoutResourceId) {
        super(context, layoutResourceId);
        this.context = context;
        this.resourceId = layoutResourceId;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View row = convertView;
        this.position = position;

        if (row == null) {

            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(resourceId, parent, false);

            holder = new ViewHolder();
            holder.imageView = (ImageView) row.findViewById(R.id.photo_grid_view);
            // stores holder with view
            row.setTag(holder);

        } else {

            holder = (ViewHolder)row.getTag();
        }

        // gets position of whichever photo you click on in the GridView
        final PhotoGridItem photoGridItem = getItem(position);

        if (photoGridItem != null) {
            Bitmap bm = photoGridItem.getImage();
            holder.imageView.setImageBitmap(bm);

            // positioning the image in the GridView slot
            holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            holder.imageView.setLayoutParams(new LinearLayout.LayoutParams(270, 270));
        }


        return row;

    }

    public class ViewHolder{
        ImageView imageView;
    }

}

photo_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_view"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#2198bb">

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/photo_grid"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:verticalSpacing="5dp"
        android:horizontalSpacing="2dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="25dp"
        android:columnWidth="100dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:scrollbarStyle="outsideOverlay"
        android:verticalScrollbarPosition="right" />

</RelativeLayout>

photo_grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/photo_grid_view"
        android:focusable="false"
        android:focusableInTouchMode="false"/>
</LinearLayout>

3 个答案:

答案 0 :(得分:2)

package com.example.slideanim;

import java.util.ArrayList;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;

public class MyGridAdapter extends BaseAdapter {
    private ArrayList<String> list = new ArrayList<String>();
    private Activity activity;
    private LayoutInflater layoutInflater;

    public MyGridAdapter(Activity activity, ArrayList<String> list) {
        // TODO Auto-generated constructor stub
        this.activity = activity;
        this.list = list;
        layoutInflater = activity.getLayoutInflater();
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return list.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int pos, View convertView, ViewGroup arg2) {
        // TODO Auto-generated method stub
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.row, null);
            holder.imageView = (ImageView) convertView
                    .findViewById(R.id.photo_grid_view);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

        holder.imageView.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(activity, "got", Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        return convertView;
    }

    private static class ViewHolder {
        public ImageView imageView;
    }

}

答案 1 :(得分:1)

最好是在图像视图中使用单击和长按,或者在gridview项目上使用两者。

如果你想在imageview上,不要设置GridViewListener并在你的适配器中尝试这个:

holder.imageView.setOnLongClickListener(new View.OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
                    //your code
        return true;
    }
});

holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(context, PhotoViewerActivity.class);
                i.putExtra("photo", byteArray);
                context.startActivity(i);
            }

        });

答案 2 :(得分:0)

- 首先检查是否有任何视图在您的gridview中可聚焦可点击或不使它们 False ,然后再次检查您的日志 - 如果存在进一步的问题,请告知我 -THanks