gridView中的OnClickItem()如何在单独的imageView中显示相同的图像

时间:2014-08-18 09:25:38

标签: android gridview hashmap imageview

GridView已经被名为“MyDir”的特定文件夹的内容填充。我的布局gallery_fragment被两个linearlayout分成两半。左边的那个有GridView,它已经填充了“MyDir”中的图像。右侧的布局有一个ImageView。

我的想法是,我可以从左侧的GridView中选择一个图像,然后它将出现在右侧的ImageView上。我不能在这个例子中使用res / drawables文件夹。

我被告知我需要使用HashMap hMap; 有人有什么建议吗?

   public class GalleryFragment4 extends Fragment {

    private ImageView imageView;
    private ImageGridViewAdapter imageAdapter;
    private GridView gridView;
    private static final String GRIDVIEW_TAG = "Android Logo";  

    @SuppressLint("UseSparseArrays")
    public HashMap<Integer, String> hMap = new HashMap<Integer, String>();

    // private LinearLayout linear;

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

        View rootView = inflater.inflate(R.layout.fragment_gallery, container,
                false);
        // assigns gridView to an object
        gridView = (GridView) rootView.findViewById(R.id.gridview);

        gridArchitecture(rootView);

        extractFiles();

        /**
         * GridView is waiting for an image to be selected
         */
        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                // image number
                int num = (position + 1);

                // When image is selected show image number
                Toast.makeText(getActivity().getApplicationContext(),
                        "image : " + num, Toast.LENGTH_SHORT).show();

            ((Context) getCameraImages(getActivity())).getApplicationContext();

            try{
                imageView.setImageResource(position);
            }catch(NullPointerException ex){

            }

            }
        });
        return rootView;
    }

    /*
     * Save image to external SD card and create new file if said file is not
     * already created
     */

    public static final String DIRECTORY_PATH = Environment
            .getExternalStorageDirectory().toString() + "/MyDir/";

//  public static final String CAMER_IMAGE_BUCKET_ID = getBucketId(DIRECTORY_PATH);

    /**
     * Matches code in MediaProvider.computeBucketValues. Should be a common
     * function.
     */
//  public static String getBucketId(String path) {
//      return String.valueOf(path.toLowerCase().hashCode());
//  }

    /**
     * Retrieve all camera images
     * 
     * @param context
     * @return
     */
    public static List<String> getCameraImages(Context context) {
        final String[] projection = { MediaStore.Images.Media.DATA };
        final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
        final String[] selectionArgs = { DIRECTORY_PATH };
        final Cursor cursor = context.getContentResolver().query(
                Images.Media.EXTERNAL_CONTENT_URI, projection, selection,
                selectionArgs, null);

        ArrayList<String> result = new ArrayList<String>(cursor.getCount());
        if (cursor.moveToFirst()) {
            final int dataColumn = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            do {
                final String data = cursor.getString(dataColumn);
                result.add(data);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return result;
    }

    private void extractFiles() {

        // Name of the folder
        final String targetPath = DIRECTORY_PATH;

        // Toast showing name of directory which images are saved to.
        Toast.makeText(getActivity().getApplicationContext(), targetPath,
                Toast.LENGTH_LONG).show();
        File targetDirector = new File(targetPath);

        final File[] files = targetDirector.listFiles();
        for (File file : files) {
            imageAdapter.add(file.getAbsolutePath());
        }
    }

    private void gridArchitecture(View rootView) {
        // Sets the Tag
        gridView.setTag(GRIDVIEW_TAG);

        /*
         * Adapt the image for the GridView format
         */
        imageAdapter = new ImageGridViewAdapter(getActivity()
                .getApplicationContext());
        gridView.setAdapter(imageAdapter);

        // Set the orientation to landscape
        getActivity().setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}

如果有任何用处,请使用ImageGridviewAdapter.java

public class ImageGridViewAdapter extends BaseAdapter {

    private Context context;
    ArrayList<String> imageList = new ArrayList<String>();

    public ImageGridViewAdapter(Context c) {
        context = c; 
    }

    void add(String path){
        imageList.add(path); 
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            //8,8,8,8
            imageView.setPadding(20, 20, 20, 20);
        } else {
            imageView = (ImageView) convertView;
        }

        // 200, 200
        Bitmap bm = decodeSampledBitmapFromUri(imageList.get(position), 100, 100);
        imageView.setImageBitmap(bm);

        return imageView;
    }

    public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {

        Bitmap bm = null;
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        options.inJustDecodeBounds = false;
        bm = BitmapFactory.decodeFile(path, options); 

        return bm;   
    }

    public int calculateInSampleSize(

        BitmapFactory.Options options, int reqWidth, int reqHeight) {
        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;    
    }
}

这是xml fragment_gallery.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/top"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/darkblue"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/center_point"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerInParent="true"
        android:orientation="horizontal" />

    <LinearLayout
        android:id="@+id/right_linear"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toRightOf="@+id/center_point"
        android:background="@drawable/normal_shape" >

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginBottom="320dp"
            android:contentDescription="@drawable/android_icon"
            android:src="@drawable/android_icon" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/left_linear"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/center_point" >

        <GridView
            android:id="@+id/gridview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:columnWidth="50dp"
            android:gravity="center"
            android:horizontalSpacing="10dip"
            android:numColumns="2"
            android:stretchMode="columnWidth"
            android:verticalSpacing="10dip" >
        </GridView>
    </LinearLayout>

</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

请检查我已更改您的文件外观并比较并相应地进行更改 的 1).GalleryFragment4.java

public class GalleryFragment4 extends Fragment {

private ImageView imageView;
private ImageGridViewAdapter imageAdapter;
private GridView gridView;
private static final String GRIDVIEW_TAG = "Android Logo";  

// Change is here 

ArrayList<String> imageList = new ArrayList<String>();


@SuppressLint("UseSparseArrays")
public HashMap<Integer, String> hMap = new HashMap<Integer, String>();

// private LinearLayout linear;

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

    View rootView = inflater.inflate(R.layout.fragment_gallery, container,
            false);
    // assigns gridView to an object
    gridView = (GridView) rootView.findViewById(R.id.gridview);
    imageview = (ImageView) rootview.findviewById(//Place_id);

    gridArchitecture(rootView);

    extractFiles();

    /**
     * GridView is waiting for an image to be selected
     */
     gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            // image number
            //int num = (position + 1);

            // When image is selected show image number
            //Toast.makeText(getActivity().getApplicationContext(),
            // "image : " + num, Toast.LENGTH_SHORT).show();

     Bitmap bm = decodeSampledBitmapFromUri(imageList.get(position), 100, 100);
    imageView.setImageBitmap(bm);

    });
    return rootView;
}


    public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {

    Bitmap bm = null;
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(path, options); 

    return bm;   
}

public int calculateInSampleSize(

    BitmapFactory.Options options, int reqWidth, int reqHeight) {
    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;    
}

/*
 * Save image to external SD card and create new file if said file is not
 * already created
 */

public static final String DIRECTORY_PATH = Environment
        .getExternalStorageDirectory().toString() + "/MyDir/";

//  public static final String CAMER_IMAGE_BUCKET_ID = getBucketId(DIRECTORY_PATH);

/**
 * Matches code in MediaProvider.computeBucketValues. Should be a common
 * function.
 */
//  public static String getBucketId(String path) {
//      return String.valueOf(path.toLowerCase().hashCode());
//  }

/**
 * Retrieve all camera images
 * 
 * @param context
 * @return
 */
public static List<String> getCameraImages(Context context) {
    final String[] projection = { MediaStore.Images.Media.DATA };
    final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
    final String[] selectionArgs = { DIRECTORY_PATH };
    final Cursor cursor = context.getContentResolver().query(
            Images.Media.EXTERNAL_CONTENT_URI, projection, selection,
            selectionArgs, null);

    ArrayList<String> result = new ArrayList<String>(cursor.getCount());
    if (cursor.moveToFirst()) {
        final int dataColumn = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        do {
            final String data = cursor.getString(dataColumn);
            result.add(data);
        } while (cursor.moveToNext());
    }
    cursor.close();
    return result;
}

private void extractFiles() {

    // Name of the folder
    final String targetPath = DIRECTORY_PATH;

    // Toast showing name of directory which images are saved to.
    Toast.makeText(getActivity().getApplicationContext(), targetPath,
            Toast.LENGTH_LONG).show();
    File targetDirector = new File(targetPath);

    final File[] files = targetDirector.listFiles();
    for (File file : files) {
    //change is here 
        imageList.add(file.getAbsolutePath());
    }
}

    private void gridArchitecture(View rootView) {
    // Sets the Tag
    gridView.setTag(GRIDVIEW_TAG);

    /*
     * Adapt the image for the GridView format
     */
    // change is here.
    imageAdapter = new ImageGridViewAdapter(getActivity()
            .getApplicationContext(),imageList);
    gridView.setAdapter(imageAdapter);

    // Set the orientation to landscape
    getActivity().setRequestedOrientation(
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}

<强> 2.ImageGridviewAdapter.java

public class ImageGridViewAdapter extends BaseAdapter {

private Context context;
ArrayList<String> imageList = new ArrayList<String>();

public ImageGridViewAdapter(Context c,ArrayList<String> imageLists) {
    context = c; 
 imageList =  imageLists;
}

//Change is here 
//    void add(String path){
//      imageList.add(path); 
 // }

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {  
        imageView = new ImageView(context);
        imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        //8,8,8,8
        imageView.setPadding(20, 20, 20, 20);
    } else {
        imageView = (ImageView) convertView;
    }

    // 200, 200
    Bitmap bm = decodeSampledBitmapFromUri(imageList.get(position), 100, 100);
    imageView.setImageBitmap(bm);

    return imageView;
}

public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {

    Bitmap bm = null;
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(path, options); 

    return bm;   
}

public int calculateInSampleSize(

    BitmapFactory.Options options, int reqWidth, int reqHeight) {
    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;    
}
}

我已经写了我做出改变的地方 如果仍然发现任何错误,则发表评论

答案 1 :(得分:0)

假设您的目标ImageView被声明为:

private ImageView targetImageView;

您需要做的就是将听众如下所示注册到gridView

gridView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, 
            long id) {
        // You know that the convertView returned from your adapter's 
        // getView method is ImageView so you can cast it here accordingly.
        targetImageView.setImageDrawable(((ImageView) view).getDrawable());
    }
});