简体   繁体   中英

I am sharing images the only first image is shared not that one which i select from view pager

I have a problem while creating app like wallpaper.

First, I used navigation drawer, then on one item I wrote following code

So my problem is that while I am sharing images the only first image is shared not that one which I select from view pager..

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    GridView lv2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        lv2= (GridView) findViewById(R.id.gridView1);

        // / Listening to GridView item click
        lv2.setAdapter(new ImageViewPager.ImageAdapter1(getApplicationContext()));
        lv2.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                Intent i = new Intent(getApplicationContext(), ImageViewPager.class);
                i.putExtra("id", position);
                startActivity(i);
            }
        });


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);

        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

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

    @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();
        FragmentManager fragmentManager=getSupportFragmentManager();

        //noinspection SimplifiableIfStatement
        if (id==R.id.abt_us)
        {
            About_Us about_us=new About_Us();
            fragmentManager.beginTransaction().replace(R.id.container,about_us).commit();
        }
        else if (id==R.id.rt_us)
        {
            Rate_Us.app_launched(this);
        }
        else if (id==R.id.exit)
        {
            finish();
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.all) {
            lv2.setAdapter(new ImageViewPager.ImageAdapter1(getApplicationContext()));
            lv2.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                    Intent i = new Intent(getApplicationContext(), ImageViewPager.class);
                    i.putExtra("id", position);
                    startActivity(i);
                }
            });
        }

        else if (id == R.id.animal) {
            lv2.setAdapter(new ImageAdapter2(this));


            //  lv2.setAdapter(new ImageAdapter2(getApplicationContext()));
            lv2.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                    Intent i = new Intent(getApplicationContext(), ImageExample.class);
                    i.putExtra("id", position);
                    startActivity(i);
                }
            });
        } 

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

ImageAdapter2.java

public class ImageAdapter2 extends BaseAdapter {
    private Context mContext;

    public ImageAdapter2(Context c)
    {
        mContext = c;
    }

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


    public Object getItem(int position)
    {

        int imageId=position;
        return imageId;

        // return mThumbIds1[position];


    }

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

    // Create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;

        if (convertView == null)
        {
            imageView = new ImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        }
        else
        {
            imageView = (ImageView) convertView;
        }
        imageView.setImageResource(mThumbIds1[position]);
        return imageView;
    }

    // References to our images in res > drawable
    public Integer[] mThumbIds1 = {
            R.drawable.images, R.drawable.images2,
            R.drawable.images3, R.drawable.images4,
            R.drawable.images5, R.drawable.images6,
            R.drawable.images7
    };
}

ImageExample.java

public class ImageExample extends Activity {
    // Declare Variable
   int position;
    Button stwp,share,save,like,shareFace,shareWhats;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set title for the ViewPager
        setTitle("ViewPager");
        // Get the view from view_pager.xml
        setContentView(R.layout.image_animal);


        stwp= (Button) findViewById(R.id.setwall);
        share= (Button) findViewById(R.id.shareWall);
        save= (Button) findViewById(R.id.saveWall);
        like= (Button) findViewById(R.id.likeWall);

        // Retrieve data from MainActivity on item click event
        Intent p = getIntent();
        position = p.getExtras().getInt("id");

        final ImageAdapter2 imageAdapter = new ImageAdapter2(this);


        final List<ImageView> images = new ArrayList<ImageView>();

        // Retrieve all the images
        for (int i = 0; i < imageAdapter.getCount(); i++) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(imageAdapter.mThumbIds1[i]);
            imageView.setScaleType(ImageView.ScaleType.CENTER);
            images.add(imageView);
        }

        // Set the images into ViewPager
        ImagePagerAdapter pageradapter = new ImagePagerAdapter(images);
        ViewPager viewpager = (ViewPager) findViewById(R.id.pager);
        viewpager.setAdapter(pageradapter);
        viewpager.setCurrentItem(position);


        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Bitmap bm;
                OutputStream output;

                bm = BitmapFactory.decodeResource(getResources(), imageAdapter.mThumbIds1[position]);
                File filepath = Environment.getExternalStorageDirectory();
                File dir = new File(filepath.getAbsolutePath() +"/Image Example/");
                dir.mkdirs();
                File file = new File(dir, "Image.jpg");
                try {

                    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                    sharingIntent.setAction(Intent.ACTION_SEND);
                      sharingIntent.setType("image/jpg");

                    output = new FileOutputStream(file);
                    bm.compress(Bitmap.CompressFormat.JPEG, 100, output);
                    output.flush();
                    output.close();
                    Uri uri = Uri.fromFile(file);
                    sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);


                    startActivity(sharingIntent);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(ImageExample.this, "unable to share..!", Toast.LENGTH_SHORT).show();


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });
    }
}

ImagePagerAdapter.java

public class ImagePagerAdapter extends PagerAdapter {

    private List<ImageView> images;

    public ImagePagerAdapter(List<ImageView> images) {
        this.images = images;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView imageView = images.get(position);
        container.addView(imageView);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(images.get(position));
    }

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

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

content_main.xml

 <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/container">
        <GridView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:columnWidth="100dp"
            android:numColumns="2"
            android:verticalSpacing="2dp"
            android:horizontalSpacing="2dp"
            android:layout_gravity="center"
            android:id="@+id/gridView1">
        </GridView>
    </FrameLayout>

image_animal.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/pager"
        android:background="#24000000"
        >
    </android.support.v4.view.ViewPager>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#616161"
        android:id="@+id/linearLayout">

        <Button
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:background="@drawable/picture"
            android:id="@+id/setwall"
            />
        <View
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1" />
        <Button
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:background="@drawable/sharenew"
            android:id="@+id/shareWall"
            />
        <View
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1" />
        <Button
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:background="@drawable/down"
            android:id="@+id/saveWall"
            />
        <View
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1" />
        <Button
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:background="@drawable/likeimage"
            android:id="@+id/likeWall"
            />
    </LinearLayout>


</RelativeLayout>

and

Menifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.a3spl.images2">
    <uses-permission android:name="android.permission.SET_WALLPAPER" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity>
            android:name=".ImageExample"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>

You need to change position to viewpager.getCurrentItem() in your share Button click :

share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Bitmap bm;
            OutputStream output;

            bm = BitmapFactory.decodeResource(getResources(), 
                      imageAdapter.mThumbIds1[viewpager.getCurrentItem()]);

            File filepath = Environment.getExternalStorageDirectory();
            File dir = new File(filepath.getAbsolutePath() +"/Image Example/");
            dir.mkdirs();

            // I HAVE MADE CHANGED HERE

            File file = new File(dir, "Image_"+System.currentTimeMillis()+".jpg");

            // KEEP REST ON THE CODE AS IT WAS

        }
    });

您应该尝试在getItemID方法中传递“位置”(目前,您始终将其传递为0,即第一个索引)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM