how to change images by using swipe in android? - android

I am using this code for showing between bunch of images.I want to show all images one by one through swipe to left or right.Can anyone help me how is it possible to make a round swipe images, it means that you be able to see the first image again after reaching the last one in the list?
and how is it possible to put arrows or part of other images in the current page just to give an ides to the user which needs to swipe to left or right for changing the current picture.
And the last question is that how am I able to make each image clickable in order to user goes to another activity page after clicking on an image? I put the function "public void onClick(View arg0) " in the adopter to go to another activity page after clicking on the images but it does not work.
thanks for your help in advance.
public class DestinationActivity extends ActionBarActivity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.destination);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
DestinationAdapter adapter = new DestinationAdapter(this);
viewPager.setAdapter(adapter);
}
The adapter class :
public class DestinationAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.ufficio_204,
R.drawable.ufficio_203,
R.drawable.ufficio_202,
R.drawable.ufficio_201
};
DestinationAdapter(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.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.destination) {
Intent intent = new Intent(context, DetailDestinationActivity.class);
context.startActivity(intent);
}
}
});
return imageView;
}
}

Try to use a View Flipper, follow this tutorial to do that
Viee Flipper

Related

Storing images in int[] matrix?

This is a code I downloaded from here. It is storing the images in an array and is displayed accordingly when I run it. I want to store the images in a matrix and do that. i.e. swipe up,down,right,left for different images. I also want to skip some positions in the matrix. some sort of picture-map kind of thing. Is it possible editing this code? Or will I have to use a completely new syntax? How do I do it?
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.chiang_mai,
R.drawable.himeji,
R.drawable.petronas_twin_tower,
R.drawable.ulm
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
All depends on the number of pictures you have.
If there are not so many, you could give TableLayout a try. However, this implies starting over. You will have to implement scrolling, for instance, yourself.
If there are many pictures, you will have to work with (one or two) adapter classes. I believe there are two basic options.
You could reuse the code you have, make as many ImagePagerAdapter s as you want to have rows, put those adapters into an array which could be the data for a VerticalViewPager (https://github.com/castorflex/VerticalViewPager, for instance). This is probably the most difficult solution, but you will also learn a lot.
You could implement a GridView which is scrollable in two dimensions and needs an adapter, a BaseAdapter for example, which is different from the adapter you have in your code. However, if you can manage the skipping of positions (which you write about and which I don't really understand) in a one-dimensional array, too, this is a viable solution.

ViewPager delete a page

How can I permanently delete a page from a view pager. I want to delete a page when the user presses a button present on that screen. I am struggling a lot with this. I read the documentation of pageradapter and found the destroyitem but it didn't help me much though. I am able to add the images in viewpager but deleting is still giving me a tough time. Please help.
Below is the code for the activity in which images are fetched and I want to delete an image on user request.
public class ImageDisplayActivity extends Activity {
private List<String> filePaths;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display1);
// Get Image Paths for the PagerAdapter
filePaths = getIntent().getExtras().getStringArrayList("filePaths");
int currPosition = getIntent().getExtras().getInt("position");
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setCurrentItem(currPosition);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
}
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return filePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = ImageDisplayActivity.this;
ImageView imageView = new ImageView(context);
int padding = 16;
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
// Get Image
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = 4;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(filePaths.get(position), bmOptions);
// Display Image
imageView.setImageBitmap(bitmap);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object imageView) {
((ViewPager) container).removeView((ImageView) imageView);
}
}
}
As #Kuffs is saying, remove the items from filePaths, then notify the adapter about that the underlying data has changed:
filePaths.remove(...); // Remove whatever you want
adapter.notifyDatasetChanged(); // Tell the adapter that it's time to update views
I am posting an answer because I cannot comment.
You can try removing it from the adapter. Add this to your destroyItem:
if(position == conditionToRemove){
filePaths.remove(position);
adapter.notifyDatasetChanged()
}
And, you'll have to make ImagePagerAdapter a global variable.
Hope this helps!

Android ViewPager onClickListener reacts even if other fragment is show

I have a ViewPager which holds two fragments. one fragment contains nothing and the other fragment contains a gridview with ImageViews.
The ImageViews have a onClickListener set.
Everything works fine so far... but when i am on the fragment which contains nothing and tap somewhere the onClickListener of the other fragments gridviews imagview reacts to my click even if its elements aren't visible.
I could change my onClickListener so that it checks which fragment is shown but is that really the way i should do it ??? it feels a bit dirty
This is my FragmentStatePageAdapter
public class OwnPagerAdapter extends FragmentStatePagerAdapter{
private BackgroundImage backgroundImage = new BackgroundImage();
private Apps apps = new Apps();
private Home_Screen ac;
public OwnPagerAdapter(FragmentManager fm, Home_Screen activity) {
super(fm);
this.ac = activity;
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return backgroundImage;
}else if(position == 1) {
return this.apps;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
This is my BaseAdapter
public class AppAdapter extends BaseAdapter {
private AppLauncher launcherListener = new AppLauncher();
private ArrayList<ApplicationInfo> appList;
private Context ctx;
public AppAdapter(ArrayList<ApplicationInfo> listOfApps, Context ctx){
this.appList = listOfApps;
this.ctx = ctx;
}
#Override
public int getCount() {
return this.appList.size();
}
#Override
public Object getItem(int i) {
ImageView v = new ImageView(this.ctx);
v.setImageDrawable(this.appList.get(i).loadIcon(this.ctx.getPackageManager()));
return v;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
if(view != null){
((ImageView) view).setImageDrawable(this.appList.get(i).loadIcon(this.ctx.getPackageManager()));
view.setTag(i);
return view;
}
ImageView v = new ImageView(this.ctx);
v.setImageDrawable(this.appList.get(i).loadIcon(this.ctx.getPackageManager()));
v.setScaleType(ImageView.ScaleType.CENTER);
v.setOnClickListener(launcherListener);
v.setTag(i);
return v;
}
private class AppLauncher implements View.OnClickListener {
#Override
public void onClick(View view) {
ctx.startActivity(ctx.getPackageManager().getLaunchIntentForPackage(appList.get((int) view.getTag()).packageName));
}
}
}
Thats my fragment class
public class Apps extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<ApplicationInfo>>{
private GridView gridview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getLoaderManager().initLoader(1, null, this).forceLoad();
View rootView = inflater.inflate(R.layout.fragment_apps, container, false);
this.gridview = (GridView)rootView.findViewById(R.id.apptable);
return rootView;
}
#Override
public Loader<ArrayList<ApplicationInfo>> onCreateLoader(int id, Bundle args) {
return new AppLoader(getActivity());
}
#Override
public void onLoadFinished(Loader<ArrayList<ApplicationInfo>> loader, ArrayList<ApplicationInfo> data) {
Toast.makeText(getActivity(), "Done with loading Apps", Toast.LENGTH_LONG).show();
this.gridview.setAdapter(new AppAdapter(data,getActivity()));
}
#Override
public void onLoaderReset(Loader<ArrayList<ApplicationInfo>> loader) {
}
}
While i cant find any specific cause to your problem i have to suggest a cleaner way of achieving the same result you're seeking, using an inner class just to capture click events is dirty and just unnecessary. it is quite possible that using this method will solve your problem as well.
Instead of using AppLauncher class which implements an OnClickListener and then set it manualy for each item, why not using an OnItemClickListener on the whole gridview ? it will take care of click events for each item and is specific only to items inside your gridview so you dont have to worry about any leaks like you would using inner classes.
In your fragment implement OnItemClickListener :
public class Apps extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<ApplicationInfo>>, OnItemClickListener
Then in your fragment's onCreate simply set the adapter to the gridview:
gridview.setOnItemClickListener(this);
and implement the necessary method:
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
getActivity().startActivity(getActivity().getPackageManager().getLaunchIntentForPackage(appList.get(position).packageName));
}
Now you can remove the OnClickListener logic from your gridview's adapter and it should work fine, my guess is it will also solve your problem, and even if not, hey at least you end up with a cleaner code.
Another thing i find odd about your code is that you override getItemId() yet always return 0, make sure this is the normal behaviour you're looking for since im not sure it is.
Good luck.

Android ViewPager - How to bring current page to the top?

I have a ViewPager/FragmentPagerAdapter combo with a negative page margin so that the pages slightly overlap each other. Problem is, the center page is not on top. The page to the left of it obscures it. I would like it so that the center page is always displayed on top. Is there an elegant way to do this?
The z-order of the pages are determined by the order of their creation, so the latter page will be resting on top of the page created earlier (refer first image below).
In normal case, this shouldn't be any problem as the pages are arrange side-by-side with no overlapping region, so the z-order doesn't really matters. However, in the case of multiple visible page with negative margin(overlapping), the selected page might be blocked partially by the page beside it.
One way to overcome this is to keep a reference of the page during instantiation and use it to change it's z-order with view.bringToFront().
To put this in code:
public class MyActivity extends Activity {
private ViewPager vp = null;
private SparseArray<View> viewCollection = new SparseArray<View>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
vp = (ViewPager)findViewById(R.id.viewpager);
vp.setPageMargin(-20);
vp.setOffscreenPageLimit(3);
vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageSelected(int pos) {
View view = viewCollection.get(pos); // ### Get target page reference
view.bringToFront(); // ### change z-order to the top
}
});
vp.setAdapter(new MyAdapter());
}
public class MyAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
View pageLayout = getLayoutInflater().inflate(R.layout.page_layout, container, false);
final Integer pageId = position;
TextView pageText = (TextView)pageLayout.findViewById(R.id.page_id);
pageText.setText(String.valueOf(position));
pageText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
vp.setCurrentItem(pageId); // ### select the clicked page
}
});
// paint gray shades onto the page background
pageLayout.setBackgroundColor(Color.argb(255, position*40, position*40, position*40));
viewCollection.put(position, pageLayout); // ### store the reference
container.addView(pageLayout);
return(pageLayout);
}
#Override
public int getCount() {
return 8; // any arbitrary number
}
#Override
public float getPageWidth(int position) {
return(0.33f);
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return (view == obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
viewCollection.remove(position); // ### remove the reference
}
}
}

Flip in ViewPager?

I'm making use of Viewpager in my application.. when the user swipes left or right, I'll show next or previous image - basically a slideshow (of images) kind of app..
If the user taps on the app, I want to flip a view in ViewPager.. a view behind every single view - user must be able to flip the view when he taps on it.
This is the code,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.... <some code> ....
viewPager = (ViewPager) findViewById(R.id.main_viewpager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
PageListener pageListener = new PageListener();
viewPager.setOnPageChangeListener((OnPageChangeListener) pageListener);
final GestureDetector tapGestureDetector = new GestureDetector(this, new TapGestureListener());
viewPager.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
tapGestureDetector.onTouchEvent(event);
return false;
}
});
}
private class TapGestureListener extends GestureDetector.SimpleOnGestureListener{
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// HERE I CAPTURED SINGLE TAP.. HOW DO I CHANGE THE VIEW OF VIEWPAGER?
return false;
}
}
I think you should set onTouchEvent to the View inside the page, not to the whole viewpager.
In the ImageViewPagerAdapter, you have
#Override
public Object instantiateItem(ViewGroup container, final int position) {
when create the view, I assume an ImageView, set the onTouchListener to it so you have a reference to the view that can be touched.
For the flipping itself take a look at this example, it's very clear.
EDIT:
here an example I copy pasted from an app I made, I cut off the actual code inside the onclicklistener because it was quite long and not relevant. I used this method because inside istantiateItem() you create the view you want to attach the listener to.
#Override
public Object instantiateItem(ViewGroup container, final int position) {
Context context = MainActivity.this;
Log.e("InstantiateItem",Integer.toString(position));
ImageView imageView = new ImageView(context);
imageView.setImageResource(mImages[position]);
imageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do some stuf when clicked...to see if it works you could try
Log.e("Click on image",Integer.toString(position));
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}

Categories

Resources