OnClickItem() in gridView how do I show the same image in a separate imageView

假装没事ソ 提交于 2020-01-14 06:22:09

问题


The GridView is already being populated by the contents of a specific folder called "MyDir". My layout gallery_fragment is split in half by two linearlayouts. The one on the left has the GridView which is already populated with the images from "MyDir". The layout on the right has an ImageView.

The idea is that I can select an image from the GridView on the left and then it will appear on the ImageView on the right. I cannot use the res/drawables folder in this instance.

I have been told I will need to use a HashMap hMap; Does anybody have any suggestions?

   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);
    }
}

If of any use here is the 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;    
    }
}

Here is the 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>

回答1:


Assuming that your target ImageView is declared as:

private ImageView targetImageView;

All you need to do is register the listener like below to your 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());
    }
});



回答2:


Just Check i have changed your file look and Compare and make change accordingly 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;    
}
}

i have write where i have made changes if still found any error then comment bellow



来源:https://stackoverflow.com/questions/25360036/onclickitem-in-gridview-how-do-i-show-the-same-image-in-a-separate-imageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!