Android Shared Element Transitions between two ViewPagers - android

I'm trying to achieve the following:
I have an item view that displays a ViewPager with images of that item and some other information. When the user taps one of the ViewPager's images, I'd like there to be a transition between the image on the first screen and the same image on another ViewPager in a new Activity.
So far, I've managed to get the basic functionality working but there are a couple of key things that do not work as expected:
The transition from ViewPager A to the second Activity with ViewPager B only works when tapping the image at index 0 or 1 in ViewPager A.
There is a return animation when pressing back from ViewPager B in the new Activity - as long as I do not swipe to another image so the transition is from the full screen mode I'd be displaying in ViewPager B to the same image in ViewPager A. When swiping to another image and pressing back - there's no animation.
Number 1 is happening because the first couple of pages of the ViewPager are instantiated when it's created so the instantiateItem method of the Adapter gets called for each of these and this is where I'm setting the transitionName.
This is proven by the fact that calling this on the ViewPager makes that issue go away and the entry animation works on all screens:
detailPager.setOffscreenPageLimit(largeNumber);
Obviously this is unsustainable, I'd much rather not have such a high off screen limit.
My question is twofold:
How do I achieve the animation for each ViewPager item without keeping all the pages in memory via the above hack?
How can I ensure that a return transition takes place when swiping to another page in ViewPager B?
I've included my code below:
ItemActivity
public class ItemActivity extends AppCompatActivity {
private static final String ITEM_TAG = "item_tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_with_fragment_container);
ButterKnife.bind(this);
if (savedInstanceState == null) {
attachFragment();
}
}
private void attachFragment() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, ItemFragment.newInstance(), ITEM_TAG)
.commit();
}
#Override
public void onActivityReenter(int resultCode, Intent data) {
super.onActivityReenter(resultCode, data);
ItemFragment fragment = (ItemFragment) getSupportFragmentManager().findFragmentByTag(ITEM_TAG);
if (fragment != null) {
fragment.onReenter(data);
}
}}
ItemFragment - This is where the first ViewPager is
public class ItemFragment extends Fragment implements MyAdapter.MyListener {
public static final String EXTRA_STARTING_ALBUM_POSITION = "extra_starting_item_position";
public static final String EXTRA_CURRENT_ALBUM_POSITION = "extra_current_item_position";
public static final String[] IMAGE_NAMES = {"One", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
private static final int FULL_SCREEN_CODE = 1234;
private Unbinder unbinder;
private Bundle tempReenterState;
private final SharedElementCallback callback = new SharedElementCallback() {
#Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
if (tempReenterState != null) {
int startingPosition = tempReenterState.getInt(EXTRA_STARTING_ALBUM_POSITION);
int currentPosition = tempReenterState.getInt(EXTRA_CURRENT_ALBUM_POSITION);
if (startingPosition != currentPosition) {
String newTransitionName = IMAGE_NAMES[currentPosition];
View newSharedElement = detailPager.findViewWithTag(newTransitionName);
if (newSharedElement != null) {
names.clear();
names.add(newTransitionName);
sharedElements.clear();
sharedElements.put(newTransitionName, newSharedElement);
}
}
tempReenterState = null;
} else {
View navigationBar = getActivity().findViewById(android.R.id.navigationBarBackground);
View statusBar = getActivity().findViewById(android.R.id.statusBarBackground);
if (navigationBar != null) {
names.add(navigationBar.getTransitionName());
sharedElements.put(navigationBar.getTransitionName(), navigationBar);
}
if (statusBar != null) {
names.add(statusBar.getTransitionName());
sharedElements.put(statusBar.getTransitionName(), statusBar);
}
}
}
};
private List<String> images = Arrays.asList("http://wowslider.com/sliders/demo-9/data/images/1293441583_nature_forest_morning_in_the_forest_015232_.jpg",
"http://wowslider.com/sliders/demo-18/data1/images/hongkong1081704.jpg",
"http://www.irishtimes.com/polopoly_fs/1.2614603.1461003507!/image/image.jpg_gen/derivatives/box_620_330/image.jpg",
"http://weknowyourdreams.com/images/sky/sky-05.jpg");
#BindView(R.id.detail_pager)
ViewPager detailPager;
public static ItemFragment newInstance() {
return new ItemFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_image_detail, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ActivityCompat.setExitSharedElementCallback(getActivity(), callback);
detailPager.setAdapter(new MyAdapter(getActivity(), images, this));
}
#Override
public void goFullScreen(final int position, View view) {
Intent intent = FullScreenActivity.newIntent(getActivity(), position, images);
startActivityForResult(intent, FULL_SCREEN_CODE, ActivityOptions.makeSceneTransitionAnimation(getActivity(), view, view.getTransitionName()).toBundle());
}
public void onReenter(Intent data) {
tempReenterState = new Bundle(data.getExtras());
int startingPosition = tempReenterState.getInt(EXTRA_STARTING_ALBUM_POSITION);
int currentPosition = tempReenterState.getInt(EXTRA_CURRENT_ALBUM_POSITION);
if (startingPosition != currentPosition) {
detailPager.setCurrentItem(currentPosition, false);
}
ActivityCompat.postponeEnterTransition(getActivity());
detailPager.post(new Runnable() {
#Override
public void run() {
ActivityCompat.startPostponedEnterTransition(getActivity());
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (unbinder != null) {
unbinder.unbind();
}
}
}
FullScreenActivity - This is where the second ViewPager is housed
public class FullScreenActivity extends AppCompatActivity {
private final SharedElementCallback callback = new SharedElementCallback() {
#Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
if (mIsReturning) {
if (currentImage == null) {
// If shared element is null, then it has been scrolled off screen and
// no longer visible. In this case we cancel the shared element transition by
// removing the shared element from the shared elements map.
names.clear();
sharedElements.clear();
} else if (selectedIndex != mCurrentPosition) {
// If the user has swiped to a different ViewPager page, then we need to
// remove the old shared element and replace it with the new shared element
// that should be transitioned instead.
names.clear();
names.add(currentImage.getTransitionName());
sharedElements.clear();
sharedElements.put(currentImage.getTransitionName(), currentImage);
}
}
}
};
private boolean mIsReturning;
private int mCurrentPosition;
private int selectedIndex;
private static final String ARG_PRESELECTED_INDEX = "arg_preselected_index";
private static final String ARG_GALLERY_IMAGES = "arg_gallery_images";
public static final String KEY_SELECTED_IMAGE_INDEX = "key_selected_image_index";
public static final String KEY_RETAINED_IMAGES = "key_retained_images";
private static final int DEFAULT_SELECTED_INDEX = 0;
private List<String> images;
private ImageAdapter adapter;
private ImageView currentImage;
#BindView(R.id.full_screen_pager)
ViewPager viewPager;
public static Intent newIntent(#NonNull final Context context, final int selectedIndex, #NonNull final List<String> images) {
Intent intent = new Intent(context, FullScreenActivity.class);
intent.putExtra(ARG_PRESELECTED_INDEX, selectedIndex);
intent.putStringArrayListExtra(ARG_GALLERY_IMAGES, new ArrayList<>(images));
return intent;
}
#CallSuper
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_full_screen);
ButterKnife.bind(this);
ActivityCompat.postponeEnterTransition(this);
ActivityCompat.setExitSharedElementCallback(this, callback);
if (savedInstanceState == null) {
selectedIndex = getIntent().getIntExtra(ARG_PRESELECTED_INDEX, 0);
mCurrentPosition = selectedIndex;
images = getIntent().getStringArrayListExtra(ARG_GALLERY_IMAGES);
} else {
selectedIndex = savedInstanceState.getInt(KEY_SELECTED_IMAGE_INDEX);
images = savedInstanceState.getStringArrayList(KEY_RETAINED_IMAGES);
}
setupViewPager(selectedIndex, images);
}
private void setupViewPager(final int selectedIndex, List<String> images) {
adapter = new ImageAdapter(this, images);
viewPager.post(new Runnable() {
#Override
public void run() {
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(selectedIndex);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mCurrentPosition = position;
}
});
ActivityCompat.startPostponedEnterTransition(FullScreenActivity.this);
}
});
}
#Override
public void finishAfterTransition() {
mIsReturning = true;
Intent data = new Intent();
data.putExtra(EXTRA_STARTING_ALBUM_POSITION, selectedIndex);
data.putExtra(EXTRA_CURRENT_ALBUM_POSITION, viewPager.getCurrentItem());
setResult(RESULT_OK, data);
super.finishAfterTransition();
}
private class ImageAdapter extends PagerAdapter {
private final LayoutInflater layoutInflater;
private final List<String> images;
private ImageLoader<ImageView> imageLoader;
public ImageAdapter(Context context, List<String> images) {
this.imageLoader = new PicassoImageLoader(context);
this.images = images;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
final ImageView imageView = (ImageView) layoutInflater.inflate(R.layout.full_image, container, false);
imageView.setTransitionName(IMAGE_NAMES[position]);
imageView.setTag(IMAGE_NAMES[position]);
imageLoader.loadImage(images.get(position), imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
currentImage = (ImageView) object;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
MyAdapter
public class MyAdapter extends PagerAdapter {
private final LayoutInflater layoutInflater;
private final List<String> images;
private final MyListener listener;
private ImageLoader<ImageView> imageLoader;
public interface MyListener {
void goFullScreen(final int position, View selected);
}
public MyAdapter(Context context, List<String> images, MyListener listener) {
this.imageLoader = new PicassoImageLoader(context);
this.layoutInflater = LayoutInflater.from(context);
this.images = images;
this.listener = listener;
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final ImageView imageView = (ImageView) layoutInflater.inflate(R.layout.pager_item_image_thing, container, false);
imageView.setTransitionName(IMAGE_NAMES[position]);
imageView.setTag(IMAGE_NAMES[position]);
if (listener != null) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.goFullScreen(position, imageView);
}
});
}
imageLoader.loadImage(images.get(position), imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
ImageLoader
public interface ImageLoader<T extends ImageView> {
void loadImage(#NonNull final Uri imageSource, #NonNull final T imageView);
void loadImage(#NonNull final String imageSource, #NonNull final T imageView);
}
PicassoImageLoader
public class PicassoImageLoader implements ImageLoader {
private final Context context;
public PicassoImageLoader(#NonNull final Context context) {
this.context = context;
}
#Override
public void loadImage(#NonNull Uri imageSource, #NonNull ImageView imageView) {
Picasso.with(context).load(imageSource).into(imageView);
}
#Override
public void loadImage(#NonNull String imageSource, #NonNull ImageView imageView) {
Picasso.with(context).load(imageSource).into(imageView);
}
}
XML Layouts
fragment_image_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/detail_pager"
android:layout_width="match_parent"
android:layout_height="390dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is the title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some other descriptive text about things"/>
</LinearLayout>
layout_full_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/full_screen_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
pager_item_thing.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager_item_image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:foreground="?android:attr/selectableItemBackgroundBorderless"
android:layout_marginBottom="16dp" />
full_image.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/full_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />

Related

ViewPager and ImageGallery

The problem is this:
When you first choose a picture - everything is fine. If you swipe, and press the "back" button, after you open another image then will open last image which will opened.
The correct position is passed through the Bundle. I don’t understand where to look for the error.
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen, container, false);
ImageView imageView = view.findViewById(R.id.image_fScreen);
Hit hit = hits.get(position);
Picasso.get().load(hit.getLargeImageURL())
.into(imageView);
container.addView(view);
return view;
}
#Override
public int getCount() {
return hits.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
DialogFragment:
public class FullScreenDialogFragment extends DialogFragment {
private ArrayList<Hit> hits;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private TextView author;
private TextView count;
private int selectedPosition;
private Button buttonShare;
private static FullScreenDialogFragment fullScreenDialogFragment;
private int rlyPosition;
public static FullScreenDialogFragment getInstance() {
if (fullScreenDialogFragment == null) {
fullScreenDialogFragment = new FullScreenDialogFragment();
}
return fullScreenDialogFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.DialogStyle);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_viewpager, container, false);
viewPager = view.findViewById(R.id.viewpager);
author = view.findViewById(R.id.author);
buttonShare = view.findViewById(R.id.btnShare);
count = view.findViewById(R.id.count);
hits = (ArrayList<Hit>) getArguments().getSerializable("hits");
selectedPosition = getArguments().getInt("position");
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(onViewPageChangeListener);
setItem(selectedPosition);
return view;
}
private void setItem(int pos) {
viewPager.setCurrentItem(pos, true);
setItemInfo(selectedPosition);
}
private void setItemInfo(int pos) {
count.setText((pos + 1) + " of " + hits.size());
Hit hit = hits.get(pos);
author.setText(hit.getUser());
}
ViewPager.OnPageChangeListener onViewPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
setItemInfo(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
I Guess the Problem is here
private void setItem(int pos) {
viewPager.setCurrentItem(pos, true);
setItemInfo(selectedPosition);
}
You might be passing the selectedPosition instead of currentPosition
Please check.
My problem was in creating DialogFramgent object.
I did it him in Singlton pattern and called it with old data.
Now in OnClick i'm created new object DialogFramget and him get new values.
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fullScreenDialog = new FullScreenDialogFragment();
fullScreenDialog.setArguments(bundle);
fullScreenDialog.show(fragmentTransaction, "");

how to fill array from JSON for image slider in android

I have image slider in android studio, but images array from inside project.
I want to use images from JSON, how to the best solution..
this is my adapter
public class adapter_image_slider extends PagerAdapter {
Context mContext;
public adapter_image_slider(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return sliderImagesId.length;
}
private int[] sliderImagesId = new int[]{
R.drawable.imghome1, R.drawable.imghome2, R.drawable.imghome3,
};
#Override
public boolean isViewFromObject(View v, Object obj) {
return v == ((ImageView) obj);
}
#Override
public Object instantiateItem(ViewGroup container, int i) {
ImageView mImageView = new ImageView(mContext);
mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mImageView.setImageResource(sliderImagesId[i]);
((ViewPager) container).addView(mImageView, 0);
return mImageView;
}
#Override
public void destroyItem(ViewGroup container, int i, Object obj) {
((ViewPager) container).removeView((ImageView) obj);
}
}
and this is my main activity :
public class activity_img_slider_json extends Fragment {
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN= {R.drawable.imghome1,R.drawable.imghome2,R.drawable.imghome3,};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_img_slider_json,null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
super.onCreate(savedInstanceState);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager)getActivity().findViewById(R.id.pager);
mPager.setAdapter(new adapter_img_slider_json(getActivity(), XMENArray));
CircleIndicator indicator = (CircleIndicator)getActivity().findViewById(R.id.indicator);
indicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
}
}
Thanks For Attention.

ViewPager work not correctly

Can not implement so: if tap to image in MainActivity - this image has to open in PreviewActivity full screen and there I can make scroll right and left use ViewPager to browse the next or previous image in the array. Now, when i tap to image, and if use in PageFragment - resultView.setImageResource(pageNumber); - then always open firts image in my array, and if use resultView.setImageURI(source); - then open true image but if swipe - always show this one image.
PageFragment - probably in this class something wrong
public class PageFragment extends Fragment {
private static final String ARGUMENT_PAGE_NUMBER = "id_test";
private int pageNumber;
private Uri source;
static PageFragment newInstance(int page) {
PageFragment pageFragment = new PageFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getActivity().getIntent();
pageNumber = i.getExtras().getInt("id_test");
source = Uri.parse("android.resource://com.test.nico/drawable/" + Images.loadImages[pageNumber]);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_pager, null);
ImageView resultView = (ImageView) view.findViewById(R.id.result_image);
// resultView.setImageURI(source);
pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
resultView.setImageResource(pageNumber);
return view;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private Context mContext;
private RecyclerView mRecyclerView;
private ImageAdapter mImageAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mImageAdapter = new ImageAdapter(mContext, Images.loadImages);
mLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mImageAdapter);
}
}
PreviewActivity
public class PreviewActivity extends FragmentActivity {
private ViewPager viewPager;
private PagerAdapter pagerAdapter;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preview);
viewPager = (ViewPager) findViewById(R.id.preview_pager);
pagerAdapter = new PreviewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
ImageAdapter
class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.Holder> {
private int[] mItemList;
private Context mContext;
ImageAdapter(Context context, int[] itemList) {
this.mContext = context;
this.mItemList = itemList;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_list, null);
return new Holder(layoutView);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
Picasso.with(mContext).load(Images.loadImages[position]).placeholder(R.drawable.ic_stub).resize(400, 750).into(holder.view);
}
#Override
public int getItemCount() {
return this.mItemList.length;
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView view;
Holder(View itemView) {
super(itemView);
mContext = itemView.getContext();
view = new ImageView(mContext);
view = (ImageView) itemView.findViewById(R.id.recycler_view);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
final Intent intent = new Intent(mContext, PreviewActivity.class);
intent.putExtra("id_test", getAdapterPosition());
mContext.startActivity(intent);
}
}
}
PreviewPagerAdapter
class PreviewPagerAdapter extends FragmentStatePagerAdapter {
private int imagesCount = Images.loadImages.length;
private int[] images = Images.loadImages;
PreviewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return imagesCount;
}
#Override
public Fragment getItem(int position) {
return PageFragment.newInstance(images[position]);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
In your PreviewActivity you have to "jump" to the position you passed.
viewpager.setCurrentItem(getIntent().getExtras().getInt("id_test"));

Using ViewPager with fragments

I have a list of images that I display in a ImageListFragment fragment of my MainActivity, clicking on one of those images should open that image as ImageDisplayFragment inside FooPager. I have created a FooPager activity so that when the image the user clicked in ImageListFragment is displayed, the user can then swipe and view all images. The problem I have is that when I click on the image I want to view in ImageListFragment, it displays the very first image in my /drawable directory instead of the actual image I click on. I am not sure what I am doing wrong.
Here is ImageListFragment:
public class ImageListFragment extends Fragment {
private int[] mImageResIds;
private OnGalleryImageSelected mListener;
public static ImageListFragment newInstance() {
return new ImageListFragment();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mListener = (OnGalleryImageSelected) context;
final Resources resources = context.getResources();
final TypedArray typedArray = resources.obtainTypedArray(R.array.images);
final int imageCount = 18;
mImageResIds = new int[imageCount];
for (int i = 0; i < imageCount; i++) {
mImageResIds[i] = typedArray.getResourceId(i, 0);
}
typedArray.recycle();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_image_list, container, false);
final Activity activity = getActivity();
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(activity));
recyclerView.setAdapter(new GalleryImageAdapter(activity));
return view;
}
class GalleryImageAdapter extends RecyclerView.Adapter<ViewHolder> {
private LayoutInflater mLayoutInflater;
public GalleryImageAdapter(Context context) {
mLayoutInflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
return new ViewHolder(mLayoutInflater
.inflate(R.layout.recycler_view, viewGroup, false));
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
final int imageResId = mImageResIds[position];
viewHolder.setData(imageResId);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(imageResId);
Intent intent = FooPager.newIntent(getActivity(),imageResId);
startActivity (intent);
// mListener.OnGalleryImageSelected(imageResId);
}
});
}
#Override
public int getItemCount() {
return mImageResIds.length;
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private ImageView mImageView;
private ViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.gallery_image);
}
private void setData(int imageResId) {
mImageView.setImageResource(imageResId);
}
}
public interface OnGalleryImageSelected {
void OnGalleryImageSelected(int imageResId);
}
}
This is what my pager activity looks like:
public class FooPager extends FragmentActivity{
public static final String EXTRA_IMAGE_ID = "meow";
private ViewPager mViewPager;
private Integer images [] = {
R.drawable.a, R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e,
R.drawable.f, R.drawable.g, R.drawable.h,R.drawable.i,R.drawable.j,
R.drawable.k, R.drawable.l, R.drawable.m,R.drawable.n,R.drawable.o,
R.drawable.p, R.drawable.q, R.drawable.r
};
public static Intent newIntent(Context packageContext, int id) {
Intent intent = new Intent(packageContext,FooPager.class);
intent.putExtra(EXTRA_IMAGE_ID,id);
return intent;
}
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView(R.layout.activity_image_pager);
mViewPager = (ViewPager) findViewById (R.id.activity_image_pager_view_pager);
FragmentManager fragmentManager = getSupportFragmentManager ();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
System.out.println(images[position]);
int id = images[position];
return ImageDetailFragment.newInstance(id);
}
#Override
public int getCount() {
return images.length;
}
});
for (int i=0; i < images.length; i++) {
mViewPager.setCurrentItem(i);
break;
}
}
}
And then ImageDetailFragmentfragment:
public class ImageDetailFragment extends Fragment {
private static final String IMAGE_ID = "imageResId";
public static ImageDetailFragment newInstance(int imageResId) {
final Bundle args = new Bundle();
args.putInt(IMAGE_ID, imageResId);
final ImageDetailFragment fragment = new ImageDetailFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_image_details, container, false);
final ImageView imageView = (ImageView) view.findViewById(R.id.gallery_image);
final Bundle args = getArguments();
imageView.setImageResource(args.getInt(IMAGE_ID));
return view;
}
}
How do I fix my FooPager activity so that it actually displays the image I clicked on from within ImageListFragment?
it displays the very first image in my /drawable directory instead of
the actual image I click on
In your FooPager Activity, this will show the first item in your viewpager. That the reason why it display the first item (i = 0 and break)
for (int i=0; i < images.length; i++) {
mViewPager.setCurrentItem(i);
break;
}
YOu need to send the position from ImageListFragment to FooPager, not imageResId and set mViewPager.setCurrentItem(position). If you send imageResId, you need to browse in you list images
for (int i=0; i < images.length; i++) {
if(images[i] == imageResId) {
mViewPager.setCurrentItem(i);
break;
}
}

Why PagerAdapter inside fragment shows only the first view?

This is my PagerAdapter.
public class SlideAdapter extends PagerAdapter{
private List<ImageView> views;
public SlideAdapter (List<ImageView> views){
this.views=views;
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView(views.get(position));
}
#Override
public int getCount() {
return views.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
#Override
public Object instantiateItem(View container, int position) {
((ViewPager) container).addView(views.get(position));
return views.get(position);
}
}
This is my fragment.
public class sportfragment extends Fragment {
private ViewPager slideviewpager;
private Boolean isContinue=true;
private AtomicInteger what=new AtomicInteger (0);
private ImageView[] indiimageview;
private List<ImageView> pics;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public sportfragment() {
}
public static sportfragment newInstance(String param1, String param2) {
sportfragment fragment = new sportfragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_sportfragment, container, false);
slideviewpager=(ViewPager) view.findViewById(R.id.slideviewpager);
ViewGroup indicatorgroup=(ViewGroup) view.findViewById(R.id.indicatorgroup);
pics=new ArrayList<ImageView>();
ImageView slide1=new ImageView(view.getContext());
slide1.setBackgroundResource(R.drawable.slide1);
pics.add(slide1);
ImageView slide2=new ImageView(view.getContext());
slide1.setBackgroundResource(R.drawable.slide2);
pics.add(slide2);
ImageView slide3=new ImageView(view.getContext());
slide1.setBackgroundResource(R.drawable.slide3);
pics.add(slide3);
ImageView slide4=new ImageView(view.getContext());
slide1.setBackgroundResource(R.drawable.slide4);
pics.add(slide4);
indiimageview=new ImageView[pics.size()];
for (int i=0;i<pics.size();i++) {
ImageView buff=new ImageView(view.getContext());
buff.setLayoutParams(new LinearLayout.LayoutParams(20,20));
buff.setPadding(5,5,5,5);
indiimageview[i]=buff;
if (i==0) {
indiimageview[i].setBackgroundResource(R.drawable.focus);
}else {
indiimageview[i].setBackgroundResource(R.drawable.blur);
}
indicatorgroup.addView(indiimageview[i]);
}
slideviewpager.setAdapter(new SlideAdapter(pics));
slideviewpager.setOnPageChangeListener(new GuidePageChangeListener());
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private final class GuidePageChangeListener implements ViewPager.OnPageChangeListener{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i=0;i<indiimageview.length;i++) {
if (i==position) {
//4 points change with viewpager
indiimageview[i].setBackgroundResource(R.drawable.focus);
} else {
indiimageview[i].setBackgroundResource(R.drawable.blur);
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
}
First page is the Image.
But other 3 is blank.
Is there any way to solve this?
ViewPagers are meant to be used with fragments, not views. This means that you should be packaging your ImageViews as Fragments rather than plain old views.
Consider the following example:
MyImageView.java
public class MyImageFragment extends Fragment {
private ImageView mImageView;
private int resourceId;
public static MyImageFragment newInstance(int resourceId) {
MyImageFragment fragment = new MyImageFragment();
Bundle args = new Bundle();
args.putInt("resource_id", resourceId);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle args = getArguments();
if (args != null && !loadedFromArgs) {
url = (String)args.getSerializable("url");
resourceId = args.getInt("in_list", -1);
loadedFromArgs = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_my_image, container, false);
mImageView = (ImageView) rootView.findViewById(R.id.image);
mImageView.setBackgroundDrawable(getResources().getDrawable(resourceId))
return rootView;
}
}
fragment_my_image.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
Now, instead of a list of ImageViews, you will have a list of MyImageFragments that your PagerAdapter will point to.

Categories

Resources