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

时间:2015-08-07 01:46:14

标签: java android listview android-studio listselectionlistener

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;


    }
}

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:1)

以下是一个简单的示例,如何通过单击gridview查看图像,但您可以在xml文件中更改为listview。

这是gridview显示。

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

此课程将以单页显示图像。

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

我使用了一些来自互联网的随机图片。列表视图中使用了相同的概念来显示图像。

<强> 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>