如何从ViewPager中保存图片?

huangapple 未分类评论47阅读模式
英文:

How to Save İmage from ViewPager?

问题

SimpleFragment.java

package com.example.duvarlar.Fragment;

import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.example.duvarlar.Adapters.MyAdapter;
import com.example.duvarlar.Listeneer.IFirebaseLoadDone;
import com.example.duvarlar.Models.Movie;
import com.example.duvarlar.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class SimpleFragment extends Fragment implements IFirebaseLoadDone, ValueEventListener {
    ViewPager viewPager;
    MyAdapter adapter;
    DatabaseReference movies;
    IFirebaseLoadDone iFirebaseLoadDone;
    Button save;

    public SimpleFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_simple, container, false);

        movies = FirebaseDatabase.getInstance().getReference("Sports");

        iFirebaseLoadDone = this;
        loadMovie();

        viewPager = (ViewPager) view.findViewById(R.id.vivi_pager);

        save = (Button) view.findViewById(R.id.bSave);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setDrawingCacheEnabled(true);
                Bitmap bitmap = viewPager.getDrawingCache();

                String root = Environment.getExternalStorageDirectory().toString();
                File newDir = new File(root + "/Android");//directory name of your choice
                newDir.mkdirs();
                Random gen = new Random();
                int n = 10000;
                n = gen.nextInt(n);
                String fotoname = "Photo-" + n + ".jpg";
                File file = new File(newDir, fotoname);
                if (file.exists()) file.delete();
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.flush();
                    out.close();
                    Toast.makeText(getActivity(), "Saved to your folder" + fotoname, Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                }
            }
        });
        return view;
    }

    private void loadMovie() {
        movies.addValueEventListener(this);
    }

    @Override
    public void onFirebaseLoadSuccess(List<Movie> movieList) {
        adapter = new MyAdapter(getContext(), movieList);
        viewPager.setAdapter(adapter);
    }

    @Override
    public void onFirebasLoadFailed(String message) {
        Toast.makeText(getContext(), "" + message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        List<Movie> movieList = new ArrayList<>();
        for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
            movieList.add(moviesSnapShot.getValue(Movie.class));
        iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
    }

    @Override
    public void onDestroy() {
        movies.removeEventListener(this);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        movies.removeEventListener(this);
        super.onStop();
    }
}

MyAdapter.java

package com.example.duvarlar.Adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.duvarlar.Models.Movie;
import com.example.duvarlar.R;
import com.squareup.picasso.Picasso;

import java.util.List;

public class MyAdapter extends PagerAdapter {
    Context context;
    List<Movie> movieList;
    LayoutInflater inflater;

    public MyAdapter(Context context, List<Movie> movieList) {
        this.context = context;
        this.movieList = movieList;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return movieList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        ((ViewPager) container).removeView((View) object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull final ViewGroup container, final int position) {
        final View view = inflater.inflate(R.layout.items, container, false);
        final ImageView movie_image = (ImageView) view.findViewById(R.id.movie_image);

        Picasso.get()
                .load(movieList.get(position).getImage())
                .fit()
                .centerCrop()
                .into(movie_image);

        container.addView(view);
        return view;
    }
}

Note: The provided code appears to be about saving images from a ViewPager to the device's storage. If you have any specific questions or issues related to this code, feel free to ask.

英文:

My problem is that it always saves the same photo when I press the Save Button. I have more than 10 photos in my Viewpager, it just saves the first one, so I can't save what I want the photo,
I want to save the open photo.

I want the photo in the open window to be saved.

items.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    android:id=&quot;@+id/gallery_root&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;&gt;

    &lt;LinearLayout
        android:id=&quot;@+id/layut&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        android:layout_centerInParent=&quot;true&quot;
        android:orientation=&quot;vertical&quot;
        android:weightSum=&quot;30&quot;&gt;

        &lt;FrameLayout
            android:id=&quot;@+id/wallpaper_preview_container&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;match_parent&quot;&gt;

            &lt;ImageView
                android:id=&quot;@+id/movie_image&quot;
                android:layout_width=&quot;match_parent&quot;
                android:layout_height=&quot;match_parent&quot; /&gt;
        &lt;/FrameLayout&gt;

    &lt;/LinearLayout&gt;

&lt;/RelativeLayout&gt;

fragment_simple.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    tools:context=&quot;.Fragment.SimpleFragment&quot;&gt;

    &lt;androidx.viewpager.widget.ViewPager
        android:id=&quot;@+id/vivi_pager&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;/&gt;

    &lt;Button
        android:id=&quot;@+id/bSave&quot;
        android:layout_width=&quot;80dp&quot;
        android:layout_height=&quot;40dp&quot;
        android:layout_alignParentTop=&quot;true&quot;
        android:layout_marginStart=&quot;15dp&quot;
        android:gravity=&quot;center&quot;
        android:layout_marginTop=&quot;150dp&quot;
        android:text=&quot;Save&quot;
        android:layout_alignParentStart=&quot;true&quot;
        android:textSize=&quot;24sp&quot;
        android:padding=&quot;0dp&quot; /&gt;
&lt;/RelativeLayout&gt;

SimpleFragment.java

package com.example.duvarlar.Fragment;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.example.duvarlar.Adapters.MyAdapter;
import com.example.duvarlar.Listeneer.IFirebaseLoadDone;
import com.example.duvarlar.Models.Movie;
import com.example.duvarlar.R;
import com.example.duvarlar.Transformer.DeptPageTransformer;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * A simple {@link Fragment} subclass.
 */
public class SimpleFragment extends Fragment implements IFirebaseLoadDone, ValueEventListener {
    ViewPager viewPager;
    MyAdapter adapter;
    DatabaseReference movies;
    IFirebaseLoadDone iFirebaseLoadDone;
    Button save;
    OutputStream outputStream;

    public SimpleFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_simple, container, false);

        movies = FirebaseDatabase.getInstance().getReference(&quot;Sports&quot;);

        iFirebaseLoadDone = this;
        loadMovie();

        viewPager = (ViewPager) view.findViewById(R.id.vivi_pager);

        save = (Button) view.findViewById(R.id.bSave);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                
                viewPager.setDrawingCacheEnabled(true);
                Bitmap bitmap = viewPager.getDrawingCache();

                String root = Environment.getExternalStorageDirectory().toString();
                File newDir = new File(root + &quot;/Android&quot;);//directory name of your choice
                newDir.mkdirs();
                Random gen = new Random();
                int n = 10000;
                n = gen.nextInt(n);
                String fotoname = &quot;Photo-&quot; + n + &quot;.jpg&quot;;
                File file = new File(newDir, fotoname);
                if (file.exists()) file.delete();
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.flush();
                    out.close();
                    Toast.makeText(getActivity(), &quot;Saved to your folder&quot; + fotoname, Toast.LENGTH_SHORT).show();

                } catch (Exception e) {

                }

            }
        });
        return view;
    }

    private void loadMovie() {
        movies.addValueEventListener(this);
    }

    @Override
    public void onFirebaseLoadSuccess(List&lt;Movie&gt; movieList) {
        adapter = new MyAdapter(getContext(), movieList);
        viewPager.setAdapter(adapter);
    }

    @Override
    public void onFirebasLoadFailed(String message) {
        Toast.makeText(getContext(), &quot;&quot; + message, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        List&lt;Movie&gt; movieList = new ArrayList&lt;&gt;();
        for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
            movieList.add(moviesSnapShot.getValue(Movie.class));
        iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
    }

    @Override
    public void onDestroy() {
        movies.removeEventListener(this);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        movies.removeEventListener(this);
        super.onStop();
    }
}

MyAdapter.java

package com.example.duvarlar.Adapters;

import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.duvarlar.Models.Movie;
import com.example.duvarlar.R;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class MyAdapter extends PagerAdapter {
    Context context;
    List&lt;Movie&gt; movieList;
    LayoutInflater inflater;
    OutputStream outputStream;


    public MyAdapter(Context context, List&lt;Movie&gt; movieList) {
        this.context = context;
        this.movieList = movieList;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return movieList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        ((ViewPager)container).removeView((View)object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull final ViewGroup container, final int position) {
        final View view = inflater.inflate(R.layout.items,container,false);
        final ImageView movie_image = (ImageView)view.findViewById(R.id.movie_image);

        Picasso.get()
                .load(movieList.get(position).getImage())
                .fit()
                .centerCrop()
                .into(movie_image);

        container.addView(view);
        return view;
    }
}

huangapple
  • 本文由 发表于 2020年4月6日 02:48:40
  • 转载请务必保留本文链接:https://java.coder-hub.com/61047743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定