how to share images using view pager - android

public class EyeLinerActivity extends Activity {
int position;
private ShareActionProvider provider;
ELImageAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eyeliner);
//ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
//adapter = new ELImageAdapter(this);
//viewPager.setAdapter(adapter);
//ViewPager.setCurrentItem(0);
ViewPager pager = (ViewPager) findViewById(R.id.view_pager);
adapter = new ELImageAdapter(this);
pager.setAdapter(new ELImageAdapter(this));
// ImageView imageView = new ImageView(context);
// imageView.setImageResource(GalImages[position]);
// if (pager.getAdapter() != null)
// pager.setAdapter(adapter);
// pager.setCurrentItem(position);
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem shareitem= (MenuItem)menu.findItem(R.id.action_share);
ShareActionProvider provider = (ShareActionProvider)shareitem.getActionProvider();
Bitmap bitmap;
OutputStream output;
//ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
bitmap = BitmapFactory.decodeResource(getResources(),adapter.GalImages[position]);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/Eye Liner/");
dir.mkdirs();
File file = new File(dir, "Image.png");
try {
Intent share = new Intent(Intent.ACTION_SEND);
share.setAction(Intent.ACTION_SEND);
share.setType("image/jpeg");
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
Uri uri = Uri.fromFile(file);
share.putExtra(Intent.EXTRA_STREAM, uri);
provider.setShareIntent(share);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
//return super.onCreateOptionsMenu(menu);
private void setShareIntent(Intent intent) {
if (provider != null) {
provider.setShareIntent(intent);
}
}
}
adapter.java
public class ELImageAdapter extends PagerAdapter {
Context context;
public int[] GalImages = new int[] {
R.drawable.l_1,
R.drawable.l_2,
R.drawable.l_3,
R.drawable.l_4,
R.drawable.l_5,
R.drawable.l_6,
R.drawable.l_7,
R.drawable.l_8,
R.drawable.l_9,
R.drawable.l_10,
R.drawable.l_11,
R.drawable.l_12,
R.drawable.l_13,
R.drawable.l_14,
R.drawable.l_15,
R.drawable.l_16,
R.drawable.l_17
};
ELImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
i want to share images .. and i am using viewpager
how can i get images ids to share.? as viewpager does not support onclickitemlistener property. kindly suggest how i can get image id to dhare

If you implement a FragmentStatePagerAdapter, each page of your ViewPager can host an instance of a Fragment of your design, with its layout defined in XML. This will allow you to include whatever Views you need to compose your custom sharing UI.
From Creating Swipe Views with Tabs | Android Developers:
FragmentStatePagerAdapter
This is best for paging across a collection of objects for which the number of pages is undetermined. It destroys fragments as the user navigates to other pages, minimizing memory usage.
For example, here's how you might use FragmentStatePagerAdapter to swipe across a collection of Fragment objects:
public class CollectionDemoActivity extends FragmentActivity {
// When requested, this adapter returns a DemoObjectFragment,
// representing an object in the collection.
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
}
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}

In your case you could change share intent on every page selected event, like following:
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
setShareIntentForPosition(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
private void setShareIntentForPosition(int currentPosition){
Bitmap bitmap;
OutputStream output;
bitmap = BitmapFactory.decodeResource(getResources(),adapter.GalImages[currentPosition]);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/Eye Liner/");
dir.mkdirs();
File file = new File(dir, "Image.png");
try {
Intent share = new Intent(Intent.ACTION_SEND);
share.setAction(Intent.ACTION_SEND);
share.setType("image/jpeg");
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
Uri uri = Uri.fromFile(file);
share.putExtra(Intent.EXTRA_STREAM, uri);
setShareIntent(share);
}
private void setShareIntent(Intent intent) {
if (provider != null) {
provider.setShareIntent(intent);
}
}

how can i get images ids to share.?
Use ViewPager.getCurrentItem() to get current image id from ViewPager:
1. Create a method in ELImageAdapter class to get current selected image id :
public int getImageId(int pos){
return GalImages[pos];
}
2. Call getImageId method using adapter object in onCreateOptionsMenu method :
int currentPos=pager.getCurrentItem();
int currentImgId=adapter.getImageId(currentPos);
Now use currentImgId id to share selected image.

File file = new File(adapter.images.get(myPager.getCurrentItem()));
Intent mShareIntent = new Intent(Intent.ACTION_SEND);
mShareIntent.setType("image/*");
mShareIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file));
startActivity(Intent.createChooser(mShareIntent,"Shareith:"));
Where adapter is object of CustomAdapter creating pages for viewpager, myPager is reference variable for ViewPager enter code here and images is arraylist storing imagepath.

Related

Share Current Image in ViewPager

I am using Glide library https://github.com/bumptech/glide (alternative of Picasso) and follow this tutorial http://blog.grafixartist.com/image-gallery-app-android-studio-1-4-glide/
Basic features work well such as show images as GridView, slide images use gesture in ViewPager. But I want to add more action like sharing and saving a current image in ViewPager, but I don't understand how to get curent position. I have tried adding Share function on activity like code below but nothing happen. I think I must put function on fragment. Maybe you can help me. Thanks.
public class DetailActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
public ArrayList<ImageModel> data = new ArrayList<>();
int pos;
Toolbar toolbar;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), data);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(pos);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#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_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_share) {
share();
return true;
}
return super.onOptionsItemSelected(item);
}
private void share() { //Nothing happen
SubsamplingScaleImageView Imgv = (SubsamplingScaleImageView) mViewPager.findViewWithTag(mViewPager.getCurrentItem());
//Imgv.setBackgroundResource(data.get(pos).getUrl());
//Imgv.setTag(pos);
Imgv.setDrawingCacheEnabled(true);
Bitmap icon = Imgv.getDrawingCache();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
String nama = getPackageName().toString();
String judul = getTitle().toString();
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
Uri uri = Uri.parse("file:///sdcard/temporary_file.jpg");
shareIntent.putExtra(Intent.EXTRA_STREAM,uri);
String sAux = "I recommend " + (judul) + " for you:\n";
sAux = sAux + "https://play.google.com/store/apps/details?id="+(nama);
shareIntent.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser( shareIntent, "Share via"));
startActivity(shareIntent);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageModel> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageModel> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position, data.get(position).getName(), data.get(position).getUrl());
}
#Override
public int getCount() {
// Show 3 total pages.
return data.size();
}
#Override
public CharSequence getPageTitle(int position) {
return data.get(position).getName();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
String name, url;
int pos;
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String ARG_IMG_TITLE = "image_title";
private static final String ARG_IMG_URL = "image_url";
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.pos = args.getInt(ARG_SECTION_NUMBER);
this.name = args.getString(ARG_IMG_TITLE);
this.url = args.getString(ARG_IMG_URL);
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String name, String url) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString(ARG_IMG_TITLE, name);
args.putString(ARG_IMG_URL, url);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
final SubsamplingScaleImageView imageView = (SubsamplingScaleImageView) rootView.findViewById(R.id.detail_image);
final ImageView share = (ImageView) rootView.findViewById(R.id.share);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //This is just test code
Toast.makeText(getContext(),
"Image + " + pos , // This pos is works great
Toast.LENGTH_LONG).show();
}
});
Glide
.with(getActivity())
.load(url)
.asBitmap()
.thumbnail(0.1f)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
imageView .setImage(ImageSource.bitmap(bitmap)
);
}
});
return rootView;
}
}
}

Fragments not updating in viewpager

I am pretty new to ViewPager and adapter world in android. I have seen this issue asked many times but did not quite understand so hoping for a simplified answer :).
I have a ViewPager with 3 tabs and each tab has a fragment. By default the user first sees tab2 where he gives some imput to generate a string. this string then needs to be taken in tab3 which generates a qr code from it.
the string from tab 2 is updated to a class and tab3 takes the string from there.
My Problem is that when i move from tab2->tab3 the qr code is not generated. But when i go tab2->tab1->tab3 it is generated. I am guessing it retains my old fragment .
Below are my class codes. Could you please let me know why is this viewpager behaviour so.
my FragementActivity class:
public class ConfigExchangeMain extends FragmentActivity {
FragmentPagerAdapter adapterViewPager;
SampleFragementPagerAdapterExchange adapter;
String sent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config_exchange_main);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
adapter=new SampleFragementPagerAdapterExchange(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(1);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
}
}
My Pager Adapter looks like
public class SampleFragementPagerAdapterExchange extends FragmentStatePagerAdapter {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"CONTACTS", "HOME", "QR+SCAN"};
private ConfigDetail context;
public SampleFragementPagerAdapterExchange(FragmentManager fm) {
super(fm);
//this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 1:
return new ConfigExchangeNFR();
case 0:
return new ConfigExchangeHome();
case 2:
return new ConfigExchangeQR();
default:
return new ConfigExchangeQR();
}
}
#Override
public int getCount() {
return PAGE_COUNT;
}
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
and my fragment in tab3 that is not updating:
public class ConfigExchangeQR extends Fragment {
ImageView iQRCode ;
int iQRDimension;
Button bScan;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
View view1 = inflater.inflate(R.layout.config_exchange_qr, container, false);
iQRCode = (ImageView)view1.findViewById(R.id.qrCode);
iQRDimension = 900;
String FinalQRCode = KeyValueDb.getPrefFinalVCard(getActivity());
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(FinalQRCode, null,
contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), iQRDimension);
try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
iQRCode.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
bScan = (Button)view1.findViewById(R.id.scan_qr);
bScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
});
return view1;
}
}
In ConfigExchangeMain class:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment= adapter.getItem(position);
if(fragment instanceof ConfigExchangeQR ){
((ConfigExchangeQR)fragment).update();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
#Override
public void onDestroy() {
super.onDestroy();
viewPager.clearOnPageChangeListeners();
}
Add this method to your ConfigExchangeQR fragment
public class ConfigExchangeQR extends Fragment {
...
public void update(){
String FinalQRCode = KeyValueDb.getPrefFinalVCard(getActivity());
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(FinalQRCode, null,
contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), iQRDimension);
try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
iQRCode.setImageBitmap(bitmap);
} catch (WriterException e) {
}
}
}
When you are currently in your second tab. The first and the third tab are preloaded (because the animation is smoother). When you switch to the first tab the third tab is unloaded -> so after switching back to the third tab it is recreated and it works for you.
The 3rd tab onCreateView is called before the 2nd tab is done, thats why it is not working. Try implementing logic inside the onResume() - to make sure it is always called when the focus is back on the fragment.
Hope this helps...
Cheers

How to use URI's with an imageAdapter

I have an ArrayList of Uri's that i want to display in a ViewPager,
this is how my code looks, I have both shown how i have put the URi into a bitmap and a drawable:
public class ImageViewActivity extends Activity {
private List<String> selectedItems;
private Uri uri1;
private Drawable drawable1;
private Bitmap bitmap1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_view);
ExtendedViewPager mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
selectedItems = new ArrayList<String>();
Intent intent = getIntent();
selectedItems = intent.getStringArrayListExtra("selectedItems");
Log.d(ImageViewActivity.class.getSimpleName(), "" + selectedItems.get(0));
uri1 = Uri.parse( selectedItems.get(0));
try {
InputStream inputStream = getContentResolver().openInputStream(uri1);
drawable1 = Drawable.createFromStream(inputStream, uri1.toString());
} catch (FileNotFoundException e) {
drawable1 = getResources().getDrawable(R.drawable.image_for_empty_url);
}
Bitmap myBitmap = BitmapFactory.decodeFile(selectedItems.get(0));
bitmap1 = myBitmap;
}
static class TouchImageAdapter extends PagerAdapter {
private static int[] images = {};
#Override
public int getCount() {
return images.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
TouchImageView img = new TouchImageView(container.getContext());
img.setImageResource(images[position]);
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
but the refference code i'm looking at, has it in the "Drawable Resource Folder", code looks like this:
public class ViewPagerExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpager_example);
ExtendedViewPager mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
}
static class TouchImageAdapter extends PagerAdapter {
private static int[] images = { R.drawable.nature_1, R.drawable.nature_2, R.drawable.nature_3, R.drawable.nature_4, R.drawable.nature_5 };
#Override
public int getCount() {
return images.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
TouchImageView img = new TouchImageView(container.getContext());
img.setImageResource(images[position]);
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
I want to use each of my URI's in the ImageAdapter, i just can't figure out how to "put them into" the ImageAdapter.
First of all get the absolute path of image from Uri Because we can not convert image into bitmap using image Uri ,so just with the help of following code you can get Absolute path
Uri ImageURI = "your image uri goes here";
String selectedImagePath = ImageFilePath.getPath(getApplicationContext(), ImageURI);
File imageFile = new File(selectedImagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
then set image bitmap in the ImageView
imageView.setImageBitmap (bitmap);
hopefully this will solve your problem.

How to share image intent with viewpager?

I need to develop an application, where I need to be able to share image from ImageView in ViewPager when user press on Share Button.
My problem:
when Ipress on Share Button the ImageView cache the next Image not the current .
public class MainActivity extends Activity {
private ViewPager pager;
private ImageView Imgv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = (ViewPager) findViewById(R.id.pager);
final Integer[] imageUrls={
R.drawable.img1 , R.drawable.img2 , R.drawable.img3 , R.drawable.img4
};
pager.setAdapter(new MyAdapter(imageUrls));
Button share = (Button) findViewById(R.id.share);
share.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Imgv.setDrawingCacheEnabled(true);
Bitmap icon = Imgv.getDrawingCache();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
Uri uri = Uri.parse("file:///sdcard/temporary_file.jpg");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.putExtra(Intent.EXTRA_STREAM,uri);
startActivity(shareIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class MyAdapter extends PagerAdapter {
private LayoutInflater inflater;
private Integer[] fimg;
public MyAdapter(Integer[] fimg ) {
this.fimg=fimg;
inflater = getLayoutInflater();
}
#Override
public Object instantiateItem(View collection, int position ) {
final View imageLayout = inflater.inflate(R.layout.imgview, null);
Imgv = (ImageView)imageLayout.findViewById(R.id.full_image_view);
Imgv.setBackgroundResource(fimg[position]);
((ViewPager) collection).addView(imageLayout ,0);
return imageLayout;
}
#Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return super.getItemPosition(object);
}
#Override
public int getCount() {
return fimg.length;
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view==((View)object);
}
#Override
public void restoreState(Parcelable arg0, ClassLoader loader) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
#Override
public void finishUpdate(View container) {
}
}
}
It is because you think that Imgv is ImageView from current visible page in ViewPager. But it isnt. In your case Imgv is ImageView from the last inflated page, but not the current visible page.
I suggest you to add tag to ImageView:
Imgv.setBackgroundResource(fimg[position]);
Imgv.setTag(position); // add this line
Then you can find your ImageView by tag:
ImageView Imgv = (ImageView)pager.findViewWithTag(pager.getCurrentItem());
Imgv.setDrawingCacheEnabled(true);
...
To avoid using the drawing cache which may sometimes mean a downscaled image, I'd check out the onPageSelected() event of the ViewPager onPageChange listener.
Save the current index, and create the file to be saved from your original asset.
The Simplest and best way to get the images is by using http://developer.android.com/reference/android/support/v4/view/ViewPager.html#getCurrentItem()
This will give you the index of the current page which is nothing but the index of the imageUrls which has the current image.
So get your bitmap from imageUrls using BitmapFactory.
BitmapFactory.decodeResource(getResources(), imageUrls[pager.getCurrentItem()]);

Call Method From Activity to Fragments

i want to build app with viewpager and display image and text from DB, and i had a button to resize Text to Small,Medium,Big size, but my problem how to make that methode and call it? this is my code
Phrase.java
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.phrase);
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
text = (ImageView)findViewById(R.id.ibText);
/* call db and store in arraylist */
....
}
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
var = arrayphrase.get(index);
phrase = var.phraseKey;
title_phrase = var.titleKey;
sound_id = var.indexkey;
return PageFragment.newInstance(index,sound_id,phrase,title_phrase);
}
#Override
public void destroyItem(View container, int position, Object object) {
// TODO Auto-generated method stub
super.destroyItem(container, position, object);
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
}
CharSequence[] sizetext = {"Small", "Medium", "Big","Cancel"};
#Override
public void onClick(View v) {
case R.id.ibText:
AlertDialog.Builder listBuilder = new AlertDialog.Builder(Phrase.this);
listBuilder.setItems(sizetext, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
if(sizetext[item].equals("Big"))
{
sizeText=24;
onUpdateSize(sizeText);
}
else if(sizetext[item].equals("Medium"))
{
sizeText=20;
onUpdateSize(sizeText);
}
else if(sizetext[item].equals("Small"))
{
sizeText=16;
onUpdateSize(sizeText);
}
}
});
AlertDialog alertList = listBuilder.create();
alertList.show();
break;
}
PageFragment.java
public class PageFragment extends Fragment {
public static PageFragment newInstance(int index,String sound, String phrase, String title_phrase) {
PageFragment pageFragment = new PageFragment();
Bundle bundle = new Bundle();
bundle.putString("title_phrase", title_phrase);
bundle.putString("sound", sound);
bundle.putString("phrase", phrase);
bundle.putInt("index", index);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inScaled = false;
options.inPreferQualityOverSpeed=true;
options.inJustDecodeBounds = false;
options.inDither = false;
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), Imgid[(int)(Math.random()*Imgid.length)], options);
//imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageBitmap(bitmap);
ScrollView sv = (ScrollView)view.findViewById(R.id.scrollView1);
LinearLayout.LayoutParams lp2= new LinearLayout.LayoutParams((int)(TorasanApp.device_width*0.7), (int) (TorasanApp.device_height*0.65),Gravity.CENTER);
sv.setLayoutParams(lp2);
sv.setBackgroundColor(Color.argb(20, 65, 65, 65));
TextView tvdata = (TextView)view.findViewById(R.id.tvDetailPhrase);
tvdata.setText(getArguments().getString("phrase"));
TextView tvtitle = (TextView)view.findViewById(R.id.tvTitlephrase);
tvtitle.setText(getArguments().getString("title_phrase"));
return view;
}
}
you see in my Phrase when onclick i have onUpdateSize(sizeText) and i want call it to change TextView tvdata fontsize that was in PageFragment.java , so how to make that method and call it? because i try but still cant
In your problem,
You can have a Fragment instance in onClick method for which you want to update textview and from there you can call any method of that class(you have to create such method in Fragment class which will update textview.).
For more understanding refer this link.
in above link Step 10 contain the method calling(viewer.updateUrl(tutUrl);) to fragment class from FragmentActivity class
And in step 8 defination of updateUrl method given which is in Fragment class
In your Fragment's onCreateView, do
mButton.setOnClickListener(new View.OnClickListener() {
AlertDialog.Builder listBuilder = new AlertDialog.Builder(Phrase.this);
listBuilder.setItems(sizetext, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
if(sizetext[item].equals("Big"))
{
sizeText=24;
onUpdateSize(sizeText);
}
else if(sizetext[item].equals("Medium"))
{
sizeText=20;
onUpdateSize(sizeText);
}
else if(sizetext[item].equals("Small"))
{
sizeText=16;
onUpdateSize(sizeText);
}
}
});
AlertDialog alertList = listBuilder.create();
alertList.show();
});
Then create accessor methods in your Activity so that your Fragment can retrieve the required fields.

Categories

Resources