How do i open an image by clicking on a listview in android?

橙三吉。 提交于 2019-12-12 00:27:05

问题


So, here is the thing. I wanted to experiment a bit. So, i wrote this program which looks for images with (.jpg) extension in my mnt/shared/Newpictures folder in my GennyMotion Emulator. In my program, i captured the name of the files with .jpg extension in a String array adapter and the file path in a filepath string array. Now, here is the part where i am blank, i have the path,name and i can get the position by clicking on the list. But how do i open the image when i click on the list. I researched online and most of the codes were too confusing. So, may be someone can suggest me an easier approach. This is what i tried so far. Thanks.

package com.example.user.imageapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

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

/**
 * Created by user on 06-08-2015.
 */


public class Splash extends Activity {
    Button load;
    String s;
    private ListView mainList;
    private String[] FilePathStrings;

    ArrayList<String>filesinFolder = GetFiles("/mnt/shared/NewPictures");



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
      //  load = (Button)findViewById(R.id.Load);
        mainList = (ListView) findViewById(R.id.imagelist);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,filesinFolder );

        mainList.setAdapter(adapter);

        mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
              //what do i put here


            }
        });




    }


    public ArrayList<String> GetFiles(String DirectoryPath)
    {
        ArrayList<String> MyFiles = new ArrayList<String>();
        File f = new File(DirectoryPath);
        f.mkdirs();

        File[] files = f.listFiles();

        FilePathStrings = new String[files.length];

        for (int i = 0; i < files.length; i++) {
            // Get the path of the image file
            if(files[i].getName().contains(".jpg")) {
                FilePathStrings[i] = files[i].getAbsolutePath();
                // Get the name image file
                MyFiles.add(files[i].getName());

            }
        }



        return MyFiles;


    }
}

回答1:


A simple way to achieve this would be to create a dialog containing an imageview and then set the imageview's image to the file. Something like this should do the job:

public void onItemclick(AdapterView<?> adapterView, View view, int pos, long id){
    String filePath = filesInFolder.get(pos);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater inflater = getLayoutInflater();
    View view = inflater.inflate(R.layout.dialog_img_preview, null);
    builder.setView(view);
    ImageView imgView = (ImageView)view.findViewById(R.id.preview_imgview);
    imgView.setImageBitmap(BitmapFactory.decodeFile(filePath));
    AlertDialog dialog = builder.create();
    dialog.show();
}



回答2:


Here is simple example, how you can view image by click on gridview but you can change to listview in xml file.

This is gridview display.

GridViewActivity.java

public class GridViewActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridview);

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(GridViewActivity.this));

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                // Send intent to SingleViewActivity
                Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);

                // Pass image index
                i.putExtra("id", position);
                startActivity(i);
            }
        });
    }
}

This class will display image in single page.

SingleViewActivity.java

public class SingleViewActivity extends Activity {

    ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_view);

        options = new DisplayImageOptions.Builder().cacheInMemory(true)
                .cacheOnDisk(true).considerExifParams(true)
                .showImageForEmptyUri(R.mipmap.ic_launcher)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                .bitmapConfig(Bitmap.Config.RGB_565).build();

        // Get intent data
        Intent i = getIntent();

        // Selected image id
        int position = i.getExtras().getInt("id");
        ImageAdapter imageAdapter = new ImageAdapter(this);

        ImageView imageView = (ImageView) findViewById(R.id.SingleView);
        //imageView.setImageResource(imageAdapter.mThumbnames[position]);
        imageLoader.displayImage(imageAdapter.mThumbnames[position],imageView,options);
    }
}

i have used some random images from internet. This same concept is used in listview for displaying image.

ImageAdapter.java

public class ImageAdapter extends BaseAdapter {

    private Context mContext;
    private LayoutInflater layoutInflater;
    ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;

    // Constructor
    public ImageAdapter(Context c) {
        mContext = c;
        layoutInflater = LayoutInflater.from(mContext);
        options = new DisplayImageOptions.Builder().cacheInMemory(true)
                .cacheOnDisk(true).considerExifParams(true)
                .showImageForEmptyUri(R.mipmap.ic_launcher)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                .bitmapConfig(Bitmap.Config.RGB_565).build();
    }

    public int getCount() {
        return mThumbnames.length;
    }

    public Integer getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

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

        ViewHolder1 holder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.grideview_item, null);
            holder = new ViewHolder1();
            holder.image = (ImageView) convertView.findViewById(R.id.imageView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder1) convertView.getTag();
        }


        // Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view
        //  which implements ImageAware interface)

        //imageLoader.displayImage("drawable://" + mThumbIds[position], holder.image);
        imageLoader.displayImage(mThumbnames[position], holder.image, options);
        //holder.image.setImageDrawable(mContext.getResources().getDrawable(mThumbIds[position]));
        return convertView;
    }

    public static class ViewHolder1 {
        ImageView image;
    }

    // Keep all Images in array
   /* public Integer[] mThumbIds = {
            R.drawable.ab, R.drawable.ac,
            R.drawable.ad, R.drawable.ae

    };*/
    public String[] mThumbnames = {
            "http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
            "http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
            "http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
            "http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
            "http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
            "http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
            "http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
            "http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg"

    };
}

gridview_item.xml

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:paddingBottom="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="10dp"
        android:scaleType="fitXY" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_gravity="center|bottom"
        android:layout_marginBottom="5dip"
        android:background="#80000000"
        android:gravity="center"
        android:text="images"
        android:textColor="#000000"
        android:textSize="20dp" />
</FrameLayout>


来源:https://stackoverflow.com/questions/31868468/how-do-i-open-an-image-by-clicking-on-a-listview-in-android

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