OnClickItem()在GridView中如何显示在一个单独的ImageView相同的图像 [英] OnClickItem() in gridView how do I show the same image in a separate imageView

查看:114
本文介绍了OnClickItem()在GridView中如何显示在一个单独的ImageView相同的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GridView控件已经由被称为MYDIR的文件夹中的内容填充。我的布局gallery_fragment是一半由两个linearlayouts分裂。左边的人都有它已经填充了来自MYDIR图像GridView控件。右边的布局有一个ImageView的。

的想法是,我可以在GridView左侧选择一个图像,然后它会出现在右侧的ImageView的。我无法使用RES /可绘制文件夹,在这种情况下。

我被告知我将需要使用HashMap HMAP;
没有任何人有什么建议吗?

 公共类GalleryFragment4扩展片段{    私人ImageView的ImageView的;
    私人ImageGridViewAdapter imageAdapter;
    私人GridView控件GridView控件;
    私有静态最后弦乐GRIDVIEW_TAG =Android的标志;    @燮pressLint(UseSparseArrays)
    公众的HashMap<整数,字符串> HMAP =新的HashMap<整数,字符串>();    //私人的LinearLayout线性的;    @覆盖
    公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
            捆绑savedInstanceState){        查看rootView = inflater.inflate(R.layout.fragment_gallery,集装箱,
                假);
        //指定GridView控件对象
        GridView控件=(GridView控件)rootView.findViewById(R.id.gridview);        gridArchitecture(rootView);        提取文件();        / **
         * GridView控件正在等待图像被选中
         * /
        gridView.setOnItemClickListener(新OnItemClickListener(){
            @覆盖
            公共无效onItemClick(适配器视图<>母公司,观景,
                    INT位置,长的id){                //图像编号
                INT NUM =(位置+ 1);                //当选择形象展示图像编号
                Toast.makeText(getActivity()。getApplicationContext(),
                        形象+ NUM,Toast.LENGTH_SHORT).show();            ((背景)getCameraImages(getActivity()))getApplicationContext();            尝试{
                imageView.setImageResource(位置);
            }赶上(NullPointerException异常前){            }            }
        });
        返回rootView;
    }    / *
     *保存图片到外部SD卡,并创建新的文件,如果说文件不
     *已创建
     * /    公共静态最后弦乐目录路径=环境
            。.getExternalStorageDirectory()的toString()+/ MYDIR /;//公共静态最后弦乐CAMER_IMAGE_BUCKET_ID = getBucketId(目录路径);    / **
     *匹配在MediaProvider.computeBucketValues​​ code。应该是一种常见的
     *功能。
     * /
//公共静态字符串getBucketId(字符串路径){
//返回将String.valueOf(path.toLowerCase()哈希code());
//}    / **
     *检索所有摄像机的图像
     *
     * @参数方面
     * @返回
     * /
    公共静态列表<串GT; getCameraImages(上下文的背景下){
        最终的String [] =投影{MediaStore.Images.Media.DATA};
        最后弦乐选择= MediaStore.Images.Media.BUCKET_ID +=;
        最终的String [] = selectionArgs两个{目录路径};
        最后光标光标= context.getContentResolver()查询(
                Images.Media.EXTERNAL_CONTENT_URI,投影,选择,
                selectionArgs两个,NULL);        ArrayList的<串GT;结果=新的ArrayList<串GT;(cursor.getCount());
        如果(cursor.moveToFirst()){
            最终诠释的DataColumn =光标
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            做{
                最终字符串数据= cursor.getString(DataColumn的);
                result.add(数据);
            }而(cursor.moveToNext());
        }
        cursor.close();
        返回结果;
    }    私人无效extractFiles(){        //该文件夹的名称
        最后弦乐TARGETPATH​​ =目录路径;        //吐司示出图像保存到目录的名称。
        Toast.makeText(getActivity()。getApplicationContext(),TARGETPATH​​,
                Toast.LENGTH_LONG).show();
        文件targetDirector =新的文件(TARGETPATH​​);        最终文件[] =文件targetDirector.listFiles();
        对于(文件文件:文件){
            imageAdapter.add(file.getAbsolutePath());
        }
    }    私人无效gridArchitecture(查看rootView){
        //设置标签
        gridView.setTag(GRIDVIEW_TAG);        / *
         *适应图像为GridView格式
         * /
        imageAdapter =新ImageGridViewAdapter(getActivity()
                .getApplicationContext());
        gridView.setAdapter(imageAdapter);        //设置方向为横向
        getActivity()。setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}

如果这里任何使用的是ImageGridviewAdapter.java

 公共类ImageGridViewAdapter延伸BaseAdapter {    私人上下文的背景下;
    ArrayList的<串GT;图像列表=新的ArrayList<串GT;();    公共ImageGridViewAdapter(上下文C){
        上下文= C;
    }    空加(字符串路径){
        imageList.add(路径);
    }    @覆盖
    公众诠释的getCount(){
        返回imageList.size();
    }    @覆盖
    公共对象的getItem(INT为arg0){
        // TODO自动生成方法存根
        返回null;
    }    @覆盖
    众长getItemId(INT位置){
        // TODO自动生成方法存根
        返回0;
    }    @覆盖
    公共查看getView(INT位置,查看convertView,父母的ViewGroup){
        ImageView的ImageView的;
        如果(convertView == NULL){
            ImageView的=新ImageView的(上下文);
            imageView.setLayoutParams(新GridView.LayoutParams(220,220));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);            // 8,8,8,8
            imageView.setPadding(20,20,20,20);
        }其他{
            ImageView的=(ImageView的)convertView;
        }        // 200,200
        位图BM =去codeSampledBitmapFromUri(imageList.get(位置),100,100);
        imageView.setImageBitmap(BM);        返回ImageView的;
    }    公共位图德codeSampledBitmapFromUri(字符串路径,INT reqWidth,诠释reqHeight){        位图BM = NULL;
        最后BitmapFactory.Options选项=新BitmapFactory.Options();
        options.inJustDe codeBounds = TRUE;
        BitmapFactory.de codeFILE(路径选择);
        options.inSampleSize = calculateInSampleSize(选项,reqWidth,reqHeight);        options.inJustDe codeBounds = FALSE;
        BM = BitmapFactory.de codeFILE(路径选择);        返回BM;
    }    公众诠释calculateInSampleSize(        BitmapFactory.Options选项,诠释reqWidth,诠释reqHeight){
        最终诠释身高= options.outHeight;
        最终诠释宽度= options.outWidth;
        INT inSampleSize = 1;        如果(高度> reqHeight ||宽度GT; reqWidth){
            如果(宽>高度){
                inSampleSize = Math.round((浮点)高度/(浮点)reqHeight);
            }其他{
                inSampleSize = Math.round((浮点)宽/(浮点)reqWidth);
            }
        }        返回inSampleSize;
    }
}

下面是XML fragment_gallery.xml

 <?XML版本=1.0编码=UTF-8&GT?;
<的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:ID =@ + ID /顶
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:背景=@彩色/ darkblue
    机器人:方向=横向>    <的LinearLayout
        机器人:ID =@ + ID / center_point
        机器人:layout_width =0dp
        机器人:layout_height =0dp
        机器人:layout_centerInParent =真
        机器人:方向=横向/>    <的LinearLayout
        机器人:ID =@ + ID / right_linear
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent
        机器人:layout_toRightOf =@ + ID / center_point
        机器人:背景=@绘制/ normal_shape>        < ImageView的
            机器人:ID =@ + ID / ImageView的
            机器人:layout_width =FILL_PARENT
            机器人:layout_height =FILL_PARENT
            机器人:layout_marginBottom =320dp
            机器人:contentDescription =@绘制/ android_icon
            机器人:SRC =@绘制/ android_icon/>
    < / LinearLayout中>    <的LinearLayout
        机器人:ID =@ + ID / left_linear
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent
        机器人:layout_alignParentLeft =真
        机器人:layout_alignRight =@ + ID / center_point>        < GridView控件
            机器人:ID =@ + ID / GridView控件
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:columnWidth时=50dp
            机器人:比重=中心
            机器人:horizo​​ntalSpacing =10dip
            机器人:为numColumns =2
            机器人:stretchMode =columnWidth时
            机器人:verticalSpacing =10dip>
        < / GridView的>
    < / LinearLayout中>< / RelativeLayout的>


解决方案

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

 私人ImageView的targetImageView;

所有你需要做的是注册听众像下面的 GridView控件

  gridView.setOnItemClickListener(新OnItemClickListener(){    @覆盖
    公共无效onItemClick(适配器视图<>母公司,观景,INT位置,
            长ID){
        //你知道convertView从你的适配器的返回
        // getView方法是ImageView的,所以你可以在这里相应施放它。
        targetImageView.setImageDrawable(((ImageView的)视图).getDrawable());
    }
});

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>

解决方案

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

这篇关于OnClickItem()在GridView中如何显示在一个单独的ImageView相同的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆