How can i getCurrentView by position in a ViewPager? - android

I need getCurrentView by position in a ViewPager
This my ViewPagerAdapter
public class TutorialViewPagerAdapter extends ViewPagerAdapter {
private LayoutInflater mInflater;
private View view;
private List<Integer> views;
public TutorialViewPagerAdapter(Activity act, List<Integer> views) {
super(act, null);
this.views = views;
this.mInflater = LayoutInflater.from(this.activity);
}
#Override
public void destroyItem(View container, int arg1, Object view) {
((ViewPager) container).removeView((View) view);
}
#Override
public int getCount() {
return views.size();
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
int viewId = (Integer) views.get(position);
this.view = mInflater.inflate(viewId, null);
((ViewPager) collection).addView(view);
return view;
}
}
And this is my activity
public class Tutorial extends FragmentActivity implements
ViewPager.OnPageChangeListener {
private List<Integer> views;
private TutorialViewPagerAdapter viewPagerAdapter;
private ViewPager viewPager;
private CirclePageIndicator circlePageIndicator;
private int currentViewId;
private View currentView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial);
init();
}
private void init() {
views = new ArrayList<Integer>();
views.add(R.layout.tutorial_step_one);
views.add(R.layout.tutorial_step_two);
views.add(R.layout.tutorial_step_three);
views.add(R.layout.tutorial_step_four);
views.add(R.layout.tutorial_step_five);
viewPagerAdapter = new TutorialViewPagerAdapter(this, views);
viewPager = (ViewPager) findViewById(R.id.steps_view_pager);
circlePageIndicator = (CirclePageIndicator) findViewById(R.id.steps_indicator);
viewPager.setAdapter(viewPagerAdapter);
viewPager.setCurrentItem(0, false);
circlePageIndicator.setViewPager(viewPager);
circlePageIndicator.setCentered(true);
circlePageIndicator.setPadding(20, 20, 20, 20);
circlePageIndicator.notifyDataSetChanged();
circlePageIndicator.setCurrentItem(0);
viewPager.setOnPageChangeListener(this);
}
#Override
public void onPageScrollStateChanged(int state) {
int currentPosition = viewPager.getCurrentItem();
circlePageIndicator.setCurrentItem(currentPosition);
enableStep(currentPosition);
}
private void enableStep(int currentPosition) {
/*viewPagerAdapter.getItemPosition(object)
currentView = viewPager.getChildAt(viewPager.getRootView());
Log.d("DEBUG", currentView.toString() + " CURRENT VIEW");*/
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
}

You could add all your created views in instantiateItem to an ArrayList<View> and then make a public method for getting a view from the ArrayList with get(position). But be carefully, as soon the Activity is finished the views could be null

Instead of ViewPagerAdapter you can use FragmentPagerAdapter which will have getItem(int position) method by using which you can easily access view.
You can take a look at this post : Android Return back to same fragment after click on goto first fragment in view pager
Hope this help!!

It's moot point. What exactly You need? Current view or view by position. Imho it is different things.
Current view:
currentView = viewPager.getCurrentItem();
Or view by index (you pass wrong parameter - should be int):
currentView = viewPager.getChildAt(currentPosition);

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, "");

OnPageChangeListener in ViewPager adapter?

I have a regular ViewPager with an adapter:
public class MyDialogFragment extends DialogFragment {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private City city;
public static MyDialogFragment newInstance() {
MyDialogFragment fragment = new MyDialogFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewPager);
city = Parcels.unwrap(getArguments().getParcelable("city"));
myViewPagerAdapter = new MyViewPagerAdapter(getContext());
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// Page changed
}
});
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public class MyViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
public MyViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.city_layout, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.cityImage);
Glide.with(context)
.load(city.getImage())
.into(imageView);
}
container.addView(view);
return view;
}
#Override
public int getCount() {
return city.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
As you can see, I have a page change listener set on my ViewPager. But I need to be able to notify the adapter when the page has changed so that I can modify the adapter's ImageView. How can I do this?
Add a method to your adapter class
public class MyViewPagerAdapter extends PagerAdapter {
...
public void pageChanged(int position) {
// Do something
}
...
}
After that in your OnPageChangeListener use that method
#Override
public void onPageSelected(int position) {
myViewPagerAdapter.pageChanged(position);
}
One approach is to create a data structure in your adapter to map the pager view to its position. A SparseArray is most efficient:
private SparseArray<View> pageMap = new SparseArray<>();
Then in the adapter's instantiateItem() method, add the view to the SparseArray:
public Object instantiateItem(ViewGroup container, int position) {
...
pageMap.put(position, view);
...
}
Now in your OnPageChangeListener you can do the following:
#Override
public void onPageSelected(int position) {
View view = adapter.getView(pos);
if (view != null) {
ImageView iv = (ImageView) view.findViewById(R.id.your_image_view);
// You now have the image view
}
}
Make sure you remove views from the SparseArray in the adapter's destroyItem() method:
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
pageMap.remove(position);
...
}
You can use the constructor with imagelist to pass and that automatically called on next page..In your code will be modified like :::
ArrayList imageList=new ArrayList<>();
imageList.add("ImagePath here");
myViewPagerAdapter = new MyViewPagerAdapter(getContext(),imageList);
viewPager.setAdapter(myViewPagerAdapter);
Then your adapter will be like ::
public class MyViewPagerAdapter extends PagerAdapter {
private Context context;
private ArrayList<String> imageList
private LayoutInflater layoutInflater;
public MyViewPagerAdapter(Context context,ArrayList<String> imageList) {
this.context = context;
this.imageList = imageList;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.city_layout, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.cityImage);
Glide.with(context)
.load(imageList.get(position)) // This will be changes like
.into(imageView);
}
container.addView(view);
return view;
}
#Override
public int getCount() {
return city.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
That done ..
After this, there are some suggestion that
- please use arraylist while using the viewpager ..
Now you just taking the parceble object from bundle..
you can do the same for the arraylist,
just receive the arraylist from the same bundle by passing the whole arraylist at once.
so you dont need to find the page change event..viewpager will automatically handle that..
Here's How to send & receiving the parceable arraylist
// while sending the list
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("citylist", new ArrayList<City>());
// while receiving the list
ArrayList<City> citylist = getIntent().getParcelableArrayListExtra("citylist");
After this just get the all image and add in the imagelist array
for (int i = 0; i < citylist.size(); i++) {
imageList.add(citylist.get(i).getImage());
}
And pass this imageList in
myViewPagerAdapter = new MyViewPagerAdapter(getContext(),imageList);
viewPager.setAdapter(myViewPagerAdapter);
Tell me if needed more assitance.

android viewpager like image gallery

im trying to create an image gallery.
i have a ViewPager that each Fragment contains an image (swipable image gallery is what im trying to accomplish).
i also have a GridView that onitemclick triggers the ViewPager in the selected position showing the clicked image.
my problem is that one swipe to right and one swipe to left shows the same image as the clicked one.
ive tried setoffscreenpagelimit with no success.
this is my viewpager activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
helper = new WeddHelper(this,"wedd.db",null,1);
pager = (ViewPager) findViewById(R.id.pager);
pager.setOnPageChangeListener(this);
Intent ing = getIntent();
curr = ing.getIntExtra("curr", 0);
byto = helper.getPhotos();
count = byto.size();
FragmentManager mg = getSupportFragmentManager();
fragments = new Vector<Fragment>();
for(int i = 0; i<count;i++){
fragments.add(Fragment.instantiate(this,GalleryFrag.class.getName()));
}
mAdapter = new FragmentAdapter(getSupportFragmentManager(), fragments, this);
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(1);
pager.setCurrentItem(curr);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mCurrentPosition = position;
curr = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
public int getClicked(){
return curr;
}
public byte[] getPhotoToBeDisplayed(){
return byto.get(curr);
}
}
this is my custom adapter:
public class FragmentAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments=null;
private FragmentManager fragmentManager=null;
private Context context;
public FragmentAdapter(FragmentManager fragmentManager,List<Fragment> fragments, Context context) {
super(fragmentManager);
this.fragments=fragments;
this.fragmentManager=fragmentManager;
this.context = context;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object)
{
super.setPrimaryItem(container,0,object);
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
fragmentManager.executePendingTransactions();
fragmentManager.saveFragmentInstanceState(fragments.get(position));
}
public void replaceItem(int position,Fragment fragment)
{
fragments.set(position, fragment);
this.notifyDataSetChanged();
}
}
and this is the fragment:
public class GalleryFrag extends Fragment {
WeddHelper helper;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.gallery_fragment, container, false);
ImageGallery myActivity = (ImageGallery) getActivity();
int curr = myActivity.getClicked();
byte[] photoToBeDisplayed = myActivity.getPhotoToBeDisplayed();
helper = new WeddHelper(getActivity(),"wedd.db", null, 1);
ArrayList<byte[]> imgs = helper.getPhotos();
Bitmap br = BitmapFactory.decodeByteArray(photoToBeDisplayed,0,photoToBeDisplayed.length);
Bitmap bi = BitmapFactory.decodeByteArray(imgs.get(curr),0,imgs.get(curr).length);
Toast.makeText(getActivity(), curr+"this is from frag", Toast.LENGTH_SHORT).show();
ImageView iv = (ImageView) v.findViewById(R.id.fragImage);
iv.setImageBitmap(br);
return v;
}
}

Pager adapter with private methods without fragments in android

Is it possible to user View pager without fragments. I google it, and all examples use fragments for view pager. I want to pager load only one item from my list, so I want to ask is it possible. Here is my code for main activity, and I want to use UpdateDisplay for viewpager. Any suggestions.
public class MainActivity extends Activity implements OnClickListener{
private Button prev, next;
private TextView tv;
private int number = 0;
private ArrayList<Integer> numbers;
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prev = (Button) findViewById(R.id.prevButton);
prev.setOnClickListener(this);
next = (Button) findViewById(R.id.nextButton);
next.setOnClickListener(this);
numbers = new ArrayList<Integer>();
for (int i=0;i<5;i++){
numbers.add(i);
Log.i("Sljedece elemente dodaje u listu", String.valueOf(i));
}
tv = (TextView) findViewById(R.id.rezultatTextView);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
updateDIsplay(number);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.prevButton:
number--;
if (number==-1){
number = 4;
}
updateDIsplay(number);
break;
case R.id.nextButton:
number++;
if (number==5){
number = 0;
}
updateDIsplay(number);
break;
}
}
private void updateDIsplay(int z){
tv.setText(String.valueOf(numbers.get(z)));
}
private class MyPagerAdapter extends PagerAdapter{
#Override
public int getCount() {
return numbers.size();
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return false;
}
}
}
yes it possible. Use a PageAdapter. When instantiateItem is called, you can inflate/instantiate your view, and this to the container. E.g:
private class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView view = new TextView(PagerActivity.this);
view.setText("Item "+position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50, position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}

Android ViewPager PagerAdapter contents without calling PagerAdapter#notifyDataSetChanged Exception

I have a ViewPager in my activity. The ViewPager shows different values on swiping the pager. But I get an IllegalStateException:
PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged!
Expected adapter item count: 0, found: 20
Pager id: com.exalt.vts:id/summarypager Pager class: class android.support.v4.view.ViewPager
Problematic adapter: class com.exalt.vts.DashBoard$MyPagerAdapter
This is my source code for PagerAdapter:
public class SamplePagerAdapter extends PagerAdapter{
List<View> pages = null;
public SamplePagerAdapter(List<View> pages){
this.pages = pages;
}
#Override
public Object instantiateItem(View collection, int position){
View v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((View) view);
}
#Override
public int getCount(){
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object){
return view.equals(object);
}
#Override
public void finishUpdate(View arg0){
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1){
}
#Override
public Parcelable saveState(){
return null;
}
#Override
public void startUpdate(View arg0){
}
}
This is the MainActivity:
public class MainActivity extends Activity {
ViewPager viewPager;
SamplePagerAdapter myPagerAdapter;
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<View> pages = new ArrayList<View>();
viewPager = (ViewPager)findViewById(R.id.myviewpager);
myPagerAdapter = new SamplePagerAdapter(pages);
viewPager.setAdapter(myPagerAdapter);
viewPager.setCurrentItem(1);
LayoutInflater inflater = LayoutInflater.from(this);
View page = inflater.inflate(R.layout.mylayout, null);
for (int i = 0; i < 20; i++) {
page = inflater.inflate(R.layout.mylayout, null);
textView = (TextView) page.findViewById(R.id.text_view);
textView.setText("Страница "+i);
pages.add(page);
}
}
I try to add 20 views in my ViewPager but I get an exception.
You either need to move the following code from where it is currently to after your for loop, so that the adapter is set after your data set is setup
myPagerAdapter = new SamplePagerAdapter(pages);
viewPager.setAdapter(myPagerAdapter);
viewPager.setCurrentItem(1);
or alternatively, you can add the following after your for loop to notify the adapter that the data set has changed since you set it up
myPagerAdapter.notifyDataSetChanged();

Categories

Resources