ViewPager with GridLayout

时间:2015-09-25 19:27:05

标签: gridview

我想创建一个ViewPager,当用户点击相册中的照片时,他可以使用ViewPager在图像之间滚动。我需要一些帮助。任何答案都是apreciate,谢谢。这是我的代码:

我的照片以全屏显示的ViewImage类:

  public class ViewImage extends Activity {
    // Declare Variable
             TextView text;
          ImageView imageview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from view_image.xml
    setContentView(R.layout.view_image);

    // Retrieve data from MainActivity on GridView item click
    Intent i = getIntent();

    // Get the position
    int position = i.getExtras().getInt("position");

    // Get String arrays FilePathStrings
    String[] filepath = i.getStringArrayExtra("filepath");

    // Get String arrays FileNameStrings
    String[] filename = i.getStringArrayExtra("filename");

    // Locate the TextView in view_image.xml
    text = (TextView) findViewById(R.id.imagetext);

    // Load the text into the TextView followed by the position
    text.setText(filename[position]);

    // Locate the ImageView in view_image.xml
    imageview = (ImageView) findViewById(R.id.full_image_view);

    // Decode the filepath with BitmapFactory followed by the position
    Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);

    // Set the decoded bitmap into ImageView
    imageview.setImageBitmap(bmp);

}
}

AlbumActivity类,在这里创建一个新专辑:

 public class AlbumActivity extends Activity implements AppCompatCallback {
private AppCompatDelegate delegate1;

private final int REQUEST_CODE_CAMERA_IMAGE = 1000;
private final int REQUEST_CODE_EXTERNAL_IMAGE = 2000;

String nameAlbum;
// Declare variables
private String[] FilePathStrings;
private String[] FileNameStrings;
private File[] listFile;
GridView grid;
GridViewAdapter adapter;
File file;
boolean deleted;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    delegate1 = AppCompatDelegate.create(this, this);

    //call the onCreate() of the AppCompatDelegate
    delegate1.onCreate(savedInstanceState);

    //use the delegate to inflate the layout
    delegate1.setContentView(R.layout.album_activity);


    Toolbar toolbar = (Toolbar) findViewById(R.id.mytoolbarr);

    delegate1.setSupportActionBar(toolbar);
    delegate1.setTitle("Your Pictures");

    Button btnChoosePicture = (Button) findViewById(R.id.addimage);
    Intent intent = getIntent();
    nameAlbum = intent.getStringExtra("nameAlbum");
    // Check for SD Card
    if (!Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
        Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
                .show();
    } else {
        // Locate the image folder in your SD Card
        file = new File(Environment.getExternalStorageDirectory()
                + File.separator + nameAlbum);
        if (file.isDirectory()) {
            listFile = file.listFiles();
            // Create a String array for FilePathStrings
            FilePathStrings = new String[listFile.length];
            // Create a String array for FileNameStrings
            FileNameStrings = new String[listFile.length];

            for (int i = 0; i < listFile.length; i++) {
                // Get the path of the image file
                FilePathStrings[i] = listFile[i].getAbsolutePath();
                // Get the name image file
                FileNameStrings[i] = listFile[i].getName();
            }
        }

        // Locate the GridView in gridview_main.xml
        grid = (GridView) findViewById(R.id.gridview);
        // Pass String arrays to LazyAdapter Class
        adapter = new GridViewAdapter(this, FilePathStrings, FileNameStrings);
        // Set the LazyAdapter to the GridView
        grid.setAdapter(adapter);

        // Capture gridview item click
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Intent i = new Intent(AlbumActivity.this, ViewImage.class);
                // Pass String arrays FilePathStrings
                i.putExtra("filepath", FilePathStrings);
                // Pass String arrays FileNameStrings
                i.putExtra("filename", FileNameStrings);
                // Pass click position
                i.putExtra("position", position);
                startActivity(i);
            }

        });
        grid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, final View view, final int position, final long id) {

                AlertDialog.Builder builder = new AlertDialog.Builder(AlbumActivity.this);


                builder.setCancelable(true);
                builder.setMessage("Are you sure you want to delete this picture ?");
                builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();

                    }

                });
                builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {


                        File filepath = Environment.getExternalStorageDirectory();
                        File dir5 = new File(filepath.getAbsolutePath()
                                + nameAlbum+FileNameStrings[position]);

                        File file3 = new File(String.valueOf(dir5));
                       deleted = file3.delete();
    adapter.notifyDataSetChanged();
                        finish();
                        startActivity(getIntent());

                        dialog.dismiss();



                    }
                });

                builder.setTitle("Delete Picture");
                AlertDialog dialog = builder.create();
                dialog.show();
                return true;
            }
        });

            }


   //select picture from external storage
        btnChoosePicture.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                // choose picture from gallery
                Intent PhotoPickerIntent = new Intent(
                        Intent.ACTION_PICK);
                File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                String pictureDirectoryPath = pictureDirectory.getPath();
                Uri data = Uri.parse(pictureDirectoryPath);
                PhotoPickerIntent.setDataAndType(data, "image/*");


                startActivityForResult(PhotoPickerIntent,
                        REQUEST_CODE_EXTERNAL_IMAGE);


            }
        });
    }
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_setting) {
        return true;
    }else if(id==android.R.id.home){
        finish();
    }

    return super.onOptionsItemSelected(item);
}


public void onActivityResult(int requestCode, int resultCode, Intent data) {


    // get image from external storage

        if(resultCode == RESULT_OK){
        if (requestCode == REQUEST_CODE_EXTERNAL_IMAGE) {
            Uri uri = data.getData();
            InputStream inputStream;
            try {
                inputStream = getContentResolver().openInputStream(uri);
                Bitmap image = BitmapFactory.decodeStream(inputStream);

                ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
                bitmapArray.add(image);

                OutputStream output;
                // Find the SD Card path
                File filepath = Environment.getExternalStorageDirectory();

    int count2 =0;
                String paranteze = "("+count2+")";
                int count1 = new File("/mnt/sdcard" +     nameAlbum).listFiles().length;
                count1 = count1 + 1;
               String nameImage = "Wallpaper_" +count1 +".jpg";
 for(int j =0;j<listFile.length;j++){
FileNameStrings[j] = listFile[j].getName();
if(FileNameStrings[j].equals(nameImage)){
    nameImage="Wallpaper_" +count1+paranteze +".jpg";
    count2++;

}
    }
                    count2++;
                    File dir = new File(filepath.getAbsolutePath()
                            + nameAlbum);

                    // Retrieve the image from the res folder


                    // Create a name for the saved image
                    file = new File(dir, nameImage);



                try {
                    inputStream = getContentResolver().openInputStream(uri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    output = new FileOutputStream(file);

                    // Compress into png format image from 0% - 100%
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100,   output);
                    output.flush();
                    output.close();

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }




    if (!Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
        Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
                .show();
    } else {
        // Locate the image folder in your SD Card
        file = new File(Environment.getExternalStorageDirectory()
                + File.separator + nameAlbum);

        if (file.isDirectory()) {
            listFile = file.listFiles();
            // Create a String array for FilePathStrings
            FilePathStrings = new String[listFile.length];
            // Create a String array for FileNameStrings
            FileNameStrings = new String[listFile.length];

            for (int i = 0; i < listFile.length; i++) {
                // Get the path of the image file
                FilePathStrings[i] = listFile[i].getAbsolutePath();
                // Get the name image file
                FileNameStrings[i] = listFile[i].getName();
                // Locate the GridView in gridview_main.xml
                grid = (GridView) findViewById(R.id.gridview);
                // Pass String arrays to LazyAdapter Class
                adapter = new GridViewAdapter(this, FilePathStrings,   FileNameStrings);
                // Set the LazyAdapter to the GridView
                grid.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
            }
        }


    }

}

@Override
public void onSupportActionModeStarted(ActionMode mode) {

}

@Override
public void onSupportActionModeFinished(ActionMode mode) {

}

@Nullable
@Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback    callback) {
    return null;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_album_activity, menu);




    return true;
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch (item.getItemId()){
        case R.id.action_add:



            // choose picture from gallery
            Intent PhotoPickerIntent = new Intent(
                    Intent.ACTION_PICK);
            File pictureDirectory =         Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            String pictureDirectoryPath = pictureDirectory.getPath();
            Uri data = Uri.parse(pictureDirectoryPath);
            PhotoPickerIntent.setDataAndType(data, "image/*");


            startActivityForResult(PhotoPickerIntent,
                    REQUEST_CODE_EXTERNAL_IMAGE);

         break;
        case R.id.action_delete:

            break;


    }
    return super.onMenuItemSelected(featureId, item);

}
  }

当然还有我的GridViewAdapter类

  public class GridViewAdapter extends BaseAdapter {
  ImageView image;
   // Declare variables
private Activity activity;
private String[] filepath;
private String[] filename;

private static LayoutInflater inflater = null;

public GridViewAdapter(Activity a, String[] fpath, String[] fname) {
    activity = a;
    filepath = fpath;
    filename = fname;
    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

public int getCount() {
    return filepath.length;

}

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

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


public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.gridview_item, null);
    // Locate the TextView in gridview_item.xml
    TextView text = (TextView) vi.findViewById(R.id.text);
    // Locate the ImageView in gridview_item.xml
     image = (ImageView) vi.findViewById(R.id.grid_image);

    // Set file name to the TextView followed by the position
    File file = new File(filepath[position]);
    Picasso.with(activity).load(file).placeholder(R.drawable.rtrt).fit().centerCrop().into(image);


    // Decode the filepath with BitmapFactory followed by the position


    // Set the decoded bitmap into ImageView
  //  image.setImageBitmap(bmp);
    return vi;
}

}

0 个答案:

没有答案