I am trying to share an image but I am unsure of how to get the image URI for here:
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, [image URI]);
startActivity(Intent.createChooser(intent, "Share image with"));
}
}
Below I have all of the code where the above was taken out of.
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.locations, R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(list, this);
getSupportActionBar().setSelectedNavigationItem(1);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(View view, int position) {
final FrameLayout imageLayout = (FrameLayout) inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
Uri uri = Uri.fromFile(null);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share image with"));
}
});
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
#Override
public void onLoadingComplete() {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
#Override
public void onLoadingCancelled() {
// Do nothing
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (itemPosition == 0){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
getSupportActionBar().setSelectedNavigationItem(1);
return true;
}
}
If anybody can help that would be great!
This is how u get URI for an image in your drawable:
Uri path = Uri.parse("android.resource://your.package.name/" + R.drawable.your_image);
Related
I add to my app ViewPager to display a set of images I get the image from database.It works fine but I need to work (Intent) to image.So where user click on image he should go to a new activity and see that picture in it.I searched for a solution and could not find the solution.
If anyone Knew the solution help me please.
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private List<SliderUtils> sliderImg;
private ImageLoader imageLoader;
public ViewPagerAdapter(List sliderImg,Context context) {
this.sliderImg = sliderImg;
this.context = context;
}
#Override
public int getCount() {
return sliderImg.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.custom_layout, null);
SliderUtils utils = sliderImg.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(utils.getSliderImageUrl(), ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher_round, android.R.drawable.ic_dialog_alert));
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position == 0){
Toast.makeText(context, "Slide 1 Clicked", Toast.LENGTH_SHORT).show();
} else if(position == 1){
Toast.makeText(context, "Slide 2 Clicked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Slide 3 Clicked", Toast.LENGTH_SHORT).show();
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
public class FoodFregmaent extends Fragment {
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
RequestQueue rq;
List<SliderUtils> sliderImg;
ViewPagerAdapter viewPagerAdapter;
String request_url = "http://===========sliedshow.php";
public FoodFregmaent() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food_fregmaent, container, false);
rq = CustomVolleyRequest.getInstance(getContext()).getRequestQueue();
sliderImg = new ArrayList<>();
viewPager = (ViewPager) view.findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout)view. findViewById(R.id.SliderDots);
sendRequest();
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.nonactive_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return view;
}
public void sendRequest(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i = 0; i < response.length(); i++){
SliderUtils sliderUtils = new SliderUtils();
try {
JSONObject jsonObject = response.getJSONObject(i);
sliderUtils.setSliderImageUrl(jsonObject.getString("imageurl"));
} catch (JSONException e) {
e.printStackTrace();
}
sliderImg.add(sliderUtils);
}
viewPagerAdapter = new ViewPagerAdapter(sliderImg, getActivity());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.ic_launcher_background));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
CustomVolleyRequest.getInstance(getContext()).addToRequestQueue(jsonArrayRequest);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);
}
public class MyTimerTask extends TimerTask {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(viewPager.getCurrentItem() == 0){
viewPager.setCurrentItem(1);
} else if(viewPager.getCurrentItem() == 1){
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
public class SliderUtils {
String imageurl;
public String getSliderImageUrl() {
return imageurl;
}
public void setSliderImageUrl(String imageurl) {
this.imageurl = imageurl;
}
}
Still I search about solution to it
You can add an Intent with a String that contains the image URL into your view.setOnClickListener within the instantiateItem() of the ViewPager
#Override
public Object instantiateItem(ViewGroup container, final int position) {
// ... Other code is omitted
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Activity2.class); // Change the name of the other activity
intent.putExtra("url", sliderImg.get(position).getSliderImageUrl()); // add the image URL to the other activity
}
});
And at the target activity, receive the url with
String url = getIntent().getStringExtra("url")
am trying to hide and show a View when imageView is being tapped , i have 3 fragments in my ViewPager so the problem is that when am on my first View and i tap the imageView it works fine (my View got hided) but when am on Fragment no. 2 or three and i tap on the imageView it never hides the View its only working on my first fragment , this is my code :
public class MainActivity extends AppCompatActivity {
private static int[] imageArray;
static ImageLoader imageLoader;
static ArrayList<String> urlArray;
static DisplayImageOptions options;
static ProgressBar spinner;
static PhotoViewAttacher mAttacher;
static Boolean isToolBarShown = true;
static Button nextButton , previousButton;
static ViewPager viewPager ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
urlArray = new ArrayList<>();
urlArray.add("http://i.imgur.com/uLRgvM8.png");
urlArray.add("http://i.imgur.com/LUuJ4FO.png");
urlArray.add("http://i.imgur.com/7SSBNBA.jpg");
// Create global configuration and initialize ImageLoader with this config
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache()).build();
ImageLoader.getInstance().init(config);
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true)
.resetViewBeforeLoading(true).build();
//initialize image view
ImageView imageView = (ImageView) findViewById(R.id.imageView);
ImageFragmentPagerAdapter imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(1);
viewPager.setAdapter(imageFragmentPagerAdapter);
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return urlArray.size();
}
#Override
public Fragment getItem(int position) {
//SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
private int position;
private ImageView imageView;
private RelativeLayout relativeLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
imageView = (ImageView) swipeView.findViewById(R.id.imageView);
spinner = (ProgressBar) swipeView.findViewById(R.id.spinner);
relativeLayout = (RelativeLayout) swipeView.findViewById(R.id.tool_bar);
Bundle bundle = getArguments();
nextButton = (Button)swipeView.findViewById(R.id.next_button);
previousButton = (Button)swipeView.findViewById(R.id.button_previous);
position = bundle.getInt("position");
Toast.makeText(getContext(),"NEW PAGE CALLED",Toast.LENGTH_SHORT).show();
if (isToolBarShown){
relativeLayout.setVisibility(View.VISIBLE);
}else {
relativeLayout.setVisibility(View.GONE);
}
mAttacher = new PhotoViewAttacher(imageView);
// viewPager.OnPageChangeListener(new ViewPager.OnPageChangeListener() {
// #Override
// public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//
// }
//
// #Override
// public void onPageSelected(int position) {
//
// loadImageView(position,imageView);
//
// }
//
// #Override
// public void onPageScrollStateChanged(int state) {
//
// }
// });
previousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(viewPager.getCurrentItem()-1,true);
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(viewPager.getCurrentItem()+1,true);
}
});
return swipeView;
}
public void loadImageView(int position, final ImageView imageView ){
imageLoader.displayImage(urlArray.get(position), imageView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mAttacher = new PhotoViewAttacher(imageView);
mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
#Override
public void onViewTap(View view, float x, float y) {
if (view == imageView){
if (relativeLayout.getVisibility() == View.VISIBLE){
isToolBarShown = false;
relativeLayout.setVisibility(View.GONE);
}else {
isToolBarShown = true;
relativeLayout.setVisibility(View.VISIBLE);
}
Log.d("OOPS","WHAT THE.., WHAT IS WRONG HERE");
}
}
});
if(mAttacher!=null){
mAttacher.update();
}else{
mAttacher = new PhotoViewAttacher(imageView);
}
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
spinner.setVisibility(View.GONE);
}
}, new ImageLoadingProgressListener() {
#Override
public void onProgressUpdate(String imageUri, View view, int current, int total) {
spinner.setVisibility(View.VISIBLE);
spinner.setProgress((current*100)/total);
}
});
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// load data here
// if (getView() != null) {
// isViewShown = true;
// // fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
// loadImageView(position , imageView);
// } else {
// isViewShown = false;
// }
}
}
}}
am trying to hide and show the RelativeView , if anybody knows whats wrong or missing in my code then please do correct me
i think you have to try fragmentstatepageradapter instead of FragmentPagerAdapter. it may help you. you can see the the difference betwwen them here :
Difference between FragmentPagerAdapter and FragmentStatePagerAdapter
You didn't provide all of code, but as you said in comments mAttacher is your static variable from outside of SwipeFragment. I think that
relativeLayout
spinner
imageLoader
are also static members from outside of SwipeFragment. If they are from your R.layout.swipe_fragment layout then you should use each relativeLayout, spinner and imageLoader instance per SwipeFragment.
Now you are swiping to another fragment and you see it. But instances of classes i mentioned above are from another fragment. And that is why it does not working for you as it should. Try to do that. And you can provide more of code.
Good luck!
Setting viewpager offscreenpagelimit mayt help you:)
mViewPager.setoffscreenpagelimit(2)
//2 is important over here.
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
//use above function to set fragment
I have 3 fragment in viewpager (LeftFragment, MidFragment and Right Fragment) LeftFragment contain a listview, when clicking on listview item,it sends an index (integer) from leftfragment to mid fragment, an image will be loaded on MidFragment. Errors here can be onCreateView happens before i set the arguments. So is there a way to solve my case. Sorry my skill english is bad. Thank you !
LeftFragment
public class LeftFragment extends Fragment{
private ListView listView;
private List<ParseObject> ob;
private ProgressDialog mProgressDialog;
private ListViewAdapter adapter;
private List<School> schoollist = null;
private View v;
MainActivity mainActivity = new MainActivity();
MidFragment midFragment = new MidFragment();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.left_fragment, container, false);
initComponent();
new RemoteDataTask().execute();
return v;
}
private void initComponent() {
listView = (ListView)v.findViewById(R.id.lv_left);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity.viewPager.setCurrentItem(1);
School school = schoollist.get(position);
midFragment.reloadData(Integer.parseInt(school.getIndex()));
}
});
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Please wait a moment...");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
schoollist = new ArrayList<School>();
try{
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("School");
query.orderByAscending("index");
ob = query.find();
for (ParseObject name : ob){
School map = new School();
map.setIndex(String.valueOf(name.get("index")));
map.setCount(String.valueOf(name.get("count")));
map.setName(String.valueOf(name.get("name")));
schoollist.add(map);
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new ListViewAdapter(getActivity(), schoollist);
listView.setAdapter(adapter);
mProgressDialog.dismiss();
super.onPreExecute();
}
}
}
MidFragment
public class MidFragment extends Fragment {
// private ProgressDialog mProgressDialog;
private ImageView mImageView;
private VideoView mVideoView;
private DisplayImageOptions options;
private ImageLoader imageLoader = ImageLoader.getInstance();
private Context mContext;
private ImageLoadingListener animateFirstListener;
private ArrayList<ParseObject> objectList = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
// mImageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mid_fragment, container, false);
initComponent(view);
mContext = container.getContext();
return view;
}
private void initComponent(View view) {
mImageView = (ImageView) view.findViewById(R.id.image);
mVideoView = (VideoView) view.findViewById(R.id.video);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mVideoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// mProgressDialog = new ProgressDialog(getActivity());
// mProgressDialog.setTitle("Please wait a moment...");
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
}
public void reloadData(int index){
// mProgressDialog.show();
objectList.clear();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Data");
query.whereEqualTo("school",(Number)index);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
objectList = (ArrayList<ParseObject>) list;
// mProgressDialog.dismiss();
if (!list.isEmpty())
openFirst();
}
});
}
private void openFirst(){
ParseObject parseObject = objectList.get(0);
ParseFile parseFile = parseObject.getParseFile("file");
if (parseObject.getNumber("type") == (Number)1){
}else{
// mVideoView.setVisibility(View.GONE);
// mImageView.setVisibility(View.VISIBLE);
imageLoader.displayImage(parseFile.getUrl(), mImageView, options, animateFirstListener);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
MainActivity
public class MainActivity extends FragmentActivity{
public static MyPagerFragment myPagerFragment;
public static ViewPager viewPager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.viewPager);
myPagerFragment = new MyPagerFragment(getSupportFragmentManager());
viewPager.setAdapter(myPagerFragment);
viewPager.setCurrentItem(1);
viewPager.setOnPageChangeListener(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) {
}
});
}
public static class MyPagerFragment extends FragmentStatePagerAdapter {
public MyPagerFragment(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return new LeftFragment();
case 1: return new MidFragment();
case 2: return new RightFragment();
default: return null;
}
}
#Override
public int getCount() {
return 3;
}
}
}
LeftFragment
public class LeftFragment extends Fragment{
OnImageSelectedListener mCallback;
public interface OnImageSelectedListener {
public void onImageSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnImageSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnImageSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onImageSelected(position);
}
}
Main Activity
public class MainActivity extends FragmentActivity implements HeadlinesFragment.OnImageSelectedListener{
public void onArticleSelected(int position) {
midFragment.setImage(position);
}
}
MidFragment
public class MidFragment extends Fragment {
setImage(int position){
//set Image here this method will be called the user select a list in left fragment
}
}
I am using ViewPager to retrieve images from remote server. Everything is working well, but the problem is I don't know how to implement pinch Zoom in/out function to it. My code is below
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
public void finishUpdate(View container) {
}
public int getCount() {
return images.length;
}
public Object instantiateItem(View view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
public void onLoadingComplete(Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
public void onLoadingCancelled() {
// Do nothing
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
public void restoreState(Parcelable state, ClassLoader loader) {
}
public Parcelable saveState() {
return null;
}
public void startUpdate(View container) {
}
}
}
if your viewpager is using an imageView then you can use touchImageView
https://github.com/MikeOrtiz/TouchImageView/blob/master/src/com/example/touch/TouchImageView.java
just replace your current imageview with this custom view. goodluck
I have a ViewPager that loads images from a remote server. My problem is, I don't know how to give it a function once a specific position is selected (not clicked). Let's say, I swipe the view pager until it reaches the specific image like image number 5, I want to show some Toast saying "image 5".
pager.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
public void finishUpdate(View container) {
}
public int getCount() {
return images.length;
}
public Object instantiateItem(View view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
public void onLoadingComplete(Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
public void onLoadingCancelled() {
// Do nothing
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
public void restoreState(Parcelable state, ClassLoader loader) {
}
public Parcelable saveState() {
return null;
}
public void startUpdate(View container) {
}
}
}
You can implement onPageChangeListener, Than you can set this pageChageListener to your ViewPager using (setOnPageChangeListener()) ...
public class ImagePagerActivity extends BaseActivity implements onPageChangeListener {
private ViewPager pager;
// other variables here
public void onCreate(Bundle savedInstanceState) {
// create view Pager
// other variables
pager.setOnPageChangeListener(this);
}
// methods for Page Change Listener
#Override
public void onPageSelected(int pos) {
if (pos==5) {
//show Toast here
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// do Nothing
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// do Noting
}
}// class def ends here
edit..
Use this short hand version
Pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
if (pos==5) {
//show Toast here
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Overridee3public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
You should use the OnPageChangeListener.
There is as onPageSelected(int position) method that you can use to get the current position.
Something like
pager.setOnPageChangeListener(this);
Then make your ImagePagerActivity implement the OnPageChangeListener interface :
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
Toast.makeText(getApplicationContext(), "image " + position, Toast.LENGTH_SHORT).show();
}
public void onPageScrollStateChanged(int state) {
}