ViewPager delete a page - android

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!

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.

PagerAdapter with TouchImageView or GestureImageView not loading images

When i am using simple imageview or AspectRatioImageView I am able to load images fetched from server. But if I am using TouchImageView or GestureImageView it is not able to load images. I see a blank screen.
Apart from using UIL,I have tried some other ways of loading images also but same result.
However when i have opened a view in viewpager and its not showing image..then if i switch to landscape mode and then again to portrait mode then it is able to load image..If i call notifyDataSetChanged() anywhere inside adapter it crashes showing InflateException
xml
<com.polites.android.GestureImageView
android:id="#+id/imagefullscreen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_gravity="center"/>
Activity
pager.setAdapter(imagePagerAdapter = new ImagePagerAdapter(ImagePagerActivity.this, posts));
pager.setCurrentItem(pos);
PageListener pageListener = new PageListener();
pager.setOnPageChangeListener(pageListener);
imagePagerAdapter.notifyDataSetChanged();
Adapter
public ImagePagerAdapter(Activity activity,
List<Post> object) {
this._activity = activity;
posts = object;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(android.R.color.transparent)
.showImageForEmptyUri(android.R.color.transparent)
.showImageOnFail(android.R.color.transparent)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(_activity));
}
#Override
public int getCount() {
return posts.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final Post post = posts.get(position);
View viewLayout = inflater.inflate(R.layout.item_pager_image, container,
false);
visualizerView = (VisualizerView) viewLayout.findViewById(R.id.visualizerView);
image = (GestureImageView) viewLayout.findViewById(R.id.imagefullscreen);
mGDescription = (TextView) viewLayout.findViewById(R.id.guggu_pager_description);
image.setVisibility(View.VISIBLE);
mGDescription.setVisibility(View.VISIBLE);
play = (ImageView) viewLayout.findViewById(R.id.play);
pause = (ImageView) viewLayout.findViewById(R.id.pause);
imageLoader.displayImage(url,images, options);
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO:pausing audio/video here
}
});
}
container.addView(viewLayout);
viewLayout.setTag("my" + position);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
The issue was because TouchImageView or GestureImageView is taking time to load image from server and view was not updated after image is being loaded.
I added-
private class PageListener extends ViewPager.SimpleOnPageChangeListener
{
public void onPageSelected(int position)
{
imagePagerAdapter.notifyDataSetChanged();
}
}
inside activity class so that view is updated whenever user swipe to new page.But with this the first view that I was opening was still showing blank..so i added
h.postDelayed(r=new Runnable()
{
#Override
public void run() {
if (mPosition == position)
{
notifyDataSetChanged();
h.removeCallbacks(r);
}
}
}, 1000);
inside instantiateItem of adapter so that first view is updated after 1 second when view is created as by that time image is fetched from server.mPosition is the position of first view that is being opened.
This completely solves my issue.

how to change images by using swipe in 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

FragmentPagerAdapter + BaseAdapter + UIL not Updating

I am trying to setup a tab title strip using swipes to switch between the fragments as demoed in the documentation here. It works, up to a point. The gridview shows all the images as required however, both fragment 1 and fragment 2 are showing the same images. It appears that fragment 2 is overwriting the images because if you click on the image in fragment 1, the fragment 1 details screen pops up (even though it shows an image from fragment 2).
Basically, I need my ImageAdapter (BaseAdapter) to show the correct images for each separate fragment. I don't see how the second fragment is interacting with the first if there are no static elements.
Edit: I tried changing to Picasso and the same error occurred so there has to be something in my code.
Edit2: I found this answer and it does let me redraw the grid when a fragment becomes visible but that causes a noticeable flicker and it is obvious the images were wrong. The problem has to lie somwhere with UIL/Picasso thinking the gridview in the separate fragments are the same object (they do have the same images but in different orders).
public void setupFragmentSwipes() {
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getFragmentManager());
mViewPager = (ViewPager) mRootView.findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
String[] array = getResources().getStringArray(R.array.SortOptions);
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new FragmentGrid();
Bundle args = new Bundle();
args.putInt("mMode", mMode);
args.putInt("mSortAorD", mSortAorD);
args.putInt("mSortType", i);
fragment.setArguments(args);
return fragment
}
#Override
public int getCount() {
return array.length;
}
#Override
public CharSequence getPageTitle(int position) {
return array[position];
}
}
FragmentGrid
public class FragmentGrid extends Fragment {
public int mode;
private ArrayList<Theme> mThemes;
private GridView listView;
private static DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
protected int mSavedPosition;
private int sortType;
private int sortAorD;
#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();
mode = args.getInt("mMode", BaseConstants.ViewModes.NORMAL);
sortType = args.getInt("mSortType", BaseConstants.Sort.POPULAR);
sortAorD = args.getInt("mSortAorD", BaseConstants.Sort.DESC);
listView = (GridView) rootView.findViewById(R.id.gridview2);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_error)
.showImageOnFail(R.drawable.ic_error)
.cacheOnDisc(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
return rootView;
}
#Override
public void onResume() {
super.onResume();
listView.setSelection(mSavedPosition);
ThemeManager tm = new ThemeManager(getActivity().getApplicationContext());
mThemes = tm.getModifiedThemeList(mode);
mThemes = tm.compare(sortType, sortAorD, checkIfTesting());
listView.setAdapter(new ImageAdapter(mThemes));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSavedPosition = position;
Intent intent = new Intent(getActivity(), ImagePagerActivity.class);
intent.putExtra("mMode", mode);
intent.putExtra("mSortAorD", sortAorD);
intent.putExtra("mSortType", sortType);
intent.putExtra("mPosition", position);
startActivity(intent);
}
});
}
public class ImageAdapter extends BaseAdapter {
ArrayList<Theme> imageAdapterThemeList;
public ImageAdapter(ArrayList<Theme> themes) {
imageAdapterThemeList = themes;
}
#Override
public int getCount() {
int result = 0;
if (imageAdapterThemeList != null) {
result = imageAdapterThemeList.size();
}
return result;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getActivity().getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
} else {
imageView = (ImageView) convertView;
}
Theme theme = imageAdapterThemeList.get(position);
imageLoader.displayImage(theme.getImageURL(), imageView, options);
return imageView;
}
}
fragment_collection_object.xml
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:horizontalSpacing="4dip"
android:numColumns="auto_fit"
android:columnWidth="150dip"
android:scrollbars="vertical"
android:stretchMode="columnWidth"
android:verticalSpacing="4dip"
android:padding="4dip" />
The only difference between your two fragment instances is that you have mSortType in your arguments Bundle set to 0 or 1 based on the page. You only use that to set up mThemes, which you never seem to use in your ImageAdapter.
So, if you are expecting your two ImageAdapter instances to return separate results, you need to either have it pay attention to mSortType or otherwise have it vary based on the page.
I encountered a problem that sounds very similar to this a while ago. It turned out to be the animations used when swapping pages and nothing to do with the pager or adapter at all. Essentially the animation resulted in fragment1 being on top of the fragment2 but completely transparent, so the user thought they were touching fragment2, but the events were received by fragment1..which makes it behave very much like the adapter was returning the wrong fragment...
In short, if you are using animations (particularly z-order altering animations) try disabling them and see if the problem goes away. If it does, you have a problem in your animations.
Hope that helps,
Good Luck.
Ok, I found the answer but I don't know why. I had to change the following from:
ArrayList<Theme> imageAdapterThemeList;
public ImageAdapter(ArrayList<Theme> themes) {
imageAdapterThemeList = themes;
}
to:
ArrayList<Theme> imageAdapterThemeList = new ArrayList<Theme>();
public ImageAdapter(ArrayList<Theme> themes) {
for (int i = 0; i< themes.size() ;i++) {
imageAdapterThemeList.add(i, themes.get(i));
}
}
I think, rather than creating a new ArrayList I was merely pointing to the old one. This new method actually recreates it but I'm sure it's not very efficient.

How Do Implement ViewPager PagerTitleStrip?

I am a noob to android and i have been using tutorials to construct a viewpager layout. However, i have not been able to find a tutorial that also shows how to implement the pagertitle strip as well. I have been able to gather bits and pieces and have the bar displaying, but I don't know how make the text display properly. Currently it shows multiple titles at once and loses sync with the pages. Any help is greatly appreciated.
public class MyPagerActivity extends Activity {
PagerTitleStrip mTitleStrip;
String myTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mypagermain);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(2);
mTitleStrip = (PagerTitleStrip) findViewById(R.id.title_strip);
//some code
}
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return 5;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.news;
view = inflater.inflate(resId, null);
LinearLayout layout0=(LinearLayout)view.findViewById(R.id.LLnews);
WebView newsfeed = (WebView) view.findViewById(R.id.webViewnews);
((ViewPager) collection).addView(view, 0);
return view;
case 1:
resId = R.layout.coinshows;
view = inflater.inflate(resId, null);
LinearLayout layout1=(LinearLayout)view.findViewById(R.id.LLcoinshows);
WebView coinshows = (WebView) view.findViewById(R.id.webViewcoinshows);
((ViewPager) collection).addView(view, 0);
return view;
}
return resId;
}
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return myTitle;
}
}
I recommend using PagerSlidingTabStrip. It's usage is very simple and the it emulates Play Store look&feel, very nice.
Usage
1.For a working implementation of this project see the sample/ folder.
Include the PagerSlidingTabStrip widget in your view. This should
usually be placed adjacent to the ViewPager it represents.
<com.astuetz.viewpager.extensions.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
2.In your onCreate method (or onCreateView for a fragment), bind the widget to the ViewPager.
// Set the pager with an adapter
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new TestAdapter(getSupportFragmentManager()));
// Bind the widget to the adapter
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
3.(Optional) If you use an OnPageChangeListener with your view pager you should set it in the widget rather than on the pager directly.
// continued from above
tabs.setOnPageChangeListener(mPageChangeListener);

Categories

Resources