Android animating ImageViews within a ViewPager - android

Hi i have a view pager that loads fragments and i'm wanting to add a bit of animation to an ImageView make it move up as the ViewPager scrolls. problem i'm having is that the viewPager creates the views for the first two pages so the animation doesnt happen on those pages. Is there is a way to detect if viewpager is scrolling or if the page has changed?
heres what i have tried so far - heres my viewPagerAdapter
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(page == 0){
view = inflater.inflate(R.layout.layout_tutorial, container, false);
}else if(page == 1){
view = inflater.inflate(R.layout.layout_tutorial, container, false);
tutImage = (ImageView)view.findViewById(R.id.tutImage);
int imageResource = getResources().getIdentifier("tut_view_2", "drawable", context.getPackageName());
Drawable tutImageDrawable = getResources().getDrawable(imageResource);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
tutImage.setBackground(tutImageDrawable);
}else{
tutImage.setBackgroundDrawable(tutImageDrawable);
}
}else if(page == 2){
view = inflater.inflate(R.layout.layout_tutorial, container, false);
tutImage = (ImageView)view.findViewById(R.id.tutImage);
int imageResource = getResources().getIdentifier("tut_view_3", "drawable", context.getPackageName());
Drawable tutImageDrawable = getResources().getDrawable(imageResource);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
tutImage.setBackground(tutImageDrawable);
}else{
tutImage.setBackgroundDrawable(tutImageDrawable);
}
heres my viewpager
public static class MyPagerAdapter extends FragmentPagerAdapter {
private Context context;
public MyPagerAdapter(android.support.v4.app.FragmentManager fragmentManager,Context c) {
super(fragmentManager);
context = c;
}
#Override
public int getCount() {
int levelCount = 4;
return levelCount;
}
// Returns the fragment to display for that page
#Override
public TutorialAdapter getItem(int position) {
String data = null;
return TutorialAdapter.newInstance(position, data, context);
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}

You need to use a OnPageChangeListener, set it to your viewpager:
viewPager.setOnPageChangeListener(myOnPageChangeListener);
The OnPageChangeListener implements some methods like:
#Override
public void onPageScrollStateChanged(int state) {}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {}
They can help you. Check this for more information: ViewPager.OnPageChangeListener!

Related

android ViewPager starts at a wrong random location after reload

I am writing a simple view pager test app that loads a bunch of data from a website and creates pages to display them.
For the most part the displaying is pretty much all works. However, it falls apart when I load a new set of data to display. When I get a new set, it loads all the data perfectly well however, instead of starting from view 0 it starts at a random location. It could start at the end or somewhere in the middle.
I want all the data to load from page 1, like a book. If you load a new book the book should start from page 1 not a random page.
Reloading calls
I've tried using GotCampDetails() which sets the local variable in the class.
viewPager.setCurrentItem(0);
in my fragment but it doesn't work. Also called notifydatasetchanged() on my adapter, still didn't work.
What am I missing?
public class ViewPagerFragment extends Fragment implements WebReadResultsListener {
private ArrayList<HashMap<String, String>> campDetails;
CustomPagerAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.camp_viewpager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (campDetails != null && ! campDetails.isEmpty()) {
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new CustomPagerAdapter(getActivity(), campDetails, viewPager);
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
}
}
#Override
public boolean GotCampDetails(ArrayList<HashMap<String, String>> campDetails) {
this.campDetails = campDetails;
return true;
}
#Override
public boolean GotCampList(ArrayList<HashMap<String, String>> campDetails) {
return false;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getFragmentManager().putFragment(outState,"fragmentInstanceSaved",getFragmentManager().findFragmentById(R.id.content));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Handle orientation changes here
}
}
Adapter:
public class CustomPagerAdapter extends PagerAdapter implements ColorChangeListener {
private ArrayList<HashMap<String, String>> campDetails;
private ViewGroup collection;
private Context mContext;
private boolean isRunning = false;
private ColorChangeListener colorChangeListener;
private int color= pink;
private int currentposition;
private ViewPager viewPager;
public CustomPagerAdapter(Context context, final ArrayList<HashMap<String, String>> campDetails, ViewPager viewPager) {
this.campDetails=campDetails;
this.mContext = context;
this.viewPager = viewPager;
colorChangeListener = (ColorChangeListener) mContext;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
currentposition = pos;
if (campDetails.get(currentposition).get("color").equals("green")) {
color = green;
} else {
color = pink;
}
ColorAppBar(color);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public Object instantiateItem(ViewGroup collection, final int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.child_item, collection, false);
if (campDetails.size() <= 0) {
Toast.makeText(mContext, "Error in getting camp details", Toast.LENGTH_SHORT).show();
return null;
}
if (campDetails.get(position).get("description").equals("RD") ) {
layout.setBackgroundColor(mContext.getResources().getColor(green));
} else {
layout.setBackgroundColor(mContext.getResources().getColor(pink));
}
collection.addView(layout);
this.collection = collection;
TextView eName = (TextView) layout.findViewById(R.id.en);
TextView nEName= (TextView) layout.findViewById(R.id.nen);
TextView textView6 = (TextView) layout.findViewById(R.id.textView6);
// ImageView nextImg = (ImageView) groupLayout.get(index).findViewById(R.id.nextImg);
eName.setText(campDetails.get(position).get("name"));
if (position+1 < campDetails.size()) {
nEName.setText(campDetails.get(position+1).get("name"));
textView6.setVisibility(View.VISIBLE);
} else {
nEName.setText("You are DONE!!");
textView6.setVisibility(View.INVISIBLE);
}
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return campDetails.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
return campDetails.get(position).get("name");
}
#Override
public void ColorAppBar(int color) {
colorChangeListener.ColorAppBar(color);
}
}
I finally managed to get it done.
I had to delay the function call setCurrentItem by a few milliseconds. Race condition? I don't know why this is the case but now it works perfectly.
Here is what I added in case someone else may find it useful:
pager.postDelayed(new Runnable() {
#Override
public void run() {
pager.setCurrentItem(pos);
}
}, 100);
I'm having trouble following the details well enough to pinpoint the problem, but this guy seems to have accomplished what you're trying to do: dynamically add and remove view to viewpager
hope it helps

Calendar Swipe View Android

I'm trying to create a calendar similar to Google Calendar on Day mode, where you swipe through the days and see the hours
I'm stuck on how to update the date as the user swipes
here's what I have:
ListView Adapter
public class ListViewItems extends ArrayAdapter{
private Activity context;
private ArrayList<String> horarios;
public ListViewItems(Activity c, ArrayList<String> h){
super(c, R.layout.listview_item, h);
this.context = c;
this.horarios = h;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup){
LayoutInflater inflater = context.getLayoutInflater();
View v = inflater.inflate(R.layout.listview_item, null, true);
TextView hor = (TextView)v.findViewById(R.id.horario);
hor.setText(horarios.get(position));
return v;
}
}
EventsFragment where I set the adapter for the Viewpage
public class EventsFragment extends Fragment {
private SharedPreferences.Editor editor;
private SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_events, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
ViewPager vp = (ViewPager)view.findViewById(R.id.viewpager);
SwipeAdapter sp = new SwipeAdapter(getActivity().getSupportFragmentManager());
vp.setAdapter(sp);
vp.setCurrentItem(249);
}
The Swipe Adapter
public class SwipeAdapter extends FragmentStatePagerAdapter {
public SwipeAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new CalendarFragment();
return fragment;
}
#Override
public int getCount() {
return 500;
}
}
And my CalendarFragment where I populate the listView with the hours of the day
public class CalendarFragment extends Fragment {
private Integer currentPosition;
public CalendarFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_calendar, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
TextView text = (TextView)view.findViewById(R.id.day);
Calendar currentDate = Calendar.getInstance();
String day = Integer.toString(currentDate.get(Calendar.DAY_OF_MONTH));
text.setText(day);
ArrayList<String> horariosFixos = new ArrayList<String>();
horariosFixos.add("01:00");
horariosFixos.add("02:00");
horariosFixos.add("03:00");
horariosFixos.add("04:00");
horariosFixos.add("05:00");
horariosFixos.add("06:00");
horariosFixos.add("07:00");
horariosFixos.add("08:00");
horariosFixos.add("09:00");
horariosFixos.add("10:00");
horariosFixos.add("11:00");
horariosFixos.add("12:00");
horariosFixos.add("13:00");
horariosFixos.add("14:00");
horariosFixos.add("15:00");
horariosFixos.add("16:00");
horariosFixos.add("17:00");
horariosFixos.add("18:00");
horariosFixos.add("19:00");
horariosFixos.add("20:00");
horariosFixos.add("21:00");
horariosFixos.add("22:00");
horariosFixos.add("23:00");
horariosFixos.add("00:00");
ListViewItems events = new ListViewItems(getActivity(),horariosFixos);
ListView events_list = (ListView)view.findViewById(R.id.events_list);
events_list.setAdapter(events);
}
It's working, but I just can't figure out a way to update the date.
I tried a few things like storing the position given on SwipeAdapter and add or subtract a day from getInstance() but it didn't seem to work
Any help would be appreciated.
Ok well I don't know if I can answer your question definitively, but I may be able to help shed some light or give you food for thought.
In my code, I set a View Pager Listener. If you can do that in your code I think it would give you the functionality you are looking for.
Below is an example from one of my apps:
public void setViewPagerListener()
{
view_pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageSelected(int position)
{
//Log.i(TAG, "position: " + position);
// on changing the page
// make respected tab selected
//actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
//Log.i(TAG, "positionOffset: " + positionOffset);
if (positionOffset >= .7)
{
handler_scrim_alpha.post(setScrimAlphaRunnable(.1f));
}
else if (positionOffset < .7 && positionOffset >= .4)
{
handler_scrim_alpha.post(setScrimAlphaRunnable(.3f));
}
else if (positionOffset < .5 & positionOffset >= .2)
{
handler_scrim_alpha.post(setScrimAlphaRunnable(.5f));
}
else if (positionOffset < .2 && !(positionOffset == 0))
{
handler_scrim_alpha.post(setScrimAlphaRunnable(.7f));
}
}
#Override
public void onPageScrollStateChanged(int scrollState)
{
/*scrollState == 0 when the pager is idle and has finished it's scroll.*/
scroll_state_global = scrollState;
if (scrollState == 0 && view_pager.getCurrentItem() == 1)
{
scroll_state_global = -1;
frame_input_scrim.setVisibility(View.INVISIBLE);
view_pager.setVisibility(View.INVISIBLE);
}
}
});
}

FragmentStatePagerAdapter returning wrong position to TextView

Ok, I have an Activity where I have viewpager and textview. Then I Have adapter that extends FragmentStatePagerAdapter, here is the code for it:
public AdapterCustomPage(FragmentManager fm, Context context, TextView TV ) {
super(fm);
mContext = context;
mTV = TV;
}
#Override
public Fragment getItem(int position) {
// Create fragment object
Fragment fragment = new ImageFragmentKatalozi();
Bundle args = new Bundle();
Log.i("Poizicija" , String.valueOf(position));
String url = Static.katalozi.getSlikeKataloga().get(position);
args.putString("url", url);
fragment.setArguments(args);
mTV.setText(String.valueOf(position + 1) + "/" + String.valueOf(maxBrojStrana));
String link = Static.katalozi.getUrl();
args.putString("linkKataloga", link);
if(position == 0){
Message.message(mContext, "Na prvoj stranici kataloga ste");
}
if(position == getCount() - 1){
Message.message(mContext, "Na poslednjoj stranici kataloga ste");
}
return fragment;
}
#Override
public int getItemPosition(Object object) {
pozicija = super.getItemPosition(object);
return super.getItemPosition(object);
}
#Override
public int getCount() {
return maxBrojStrana;
}
And finally I have fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_katalozi_slike, container, false);
args = getArguments();
imageView = (TouchImageView) rootView.findViewById(R.id.imageViewAdapterZaListanjeKataloga);
Picasso.with(getActivity()).load(args.getString("url")).placeholder(R.drawable.load).error(R.drawable.error).into(imageView);
return rootView;
}
Now, the problem is, my TextView in the main activity isnt giving me back right positions for the fragment. It gives good getCount position, but when I slide to the right it goes + 1, when I slide to the left, it goes down to 0. When I put the whole textView code and xml in the fragment section, it works good, but then it slides with fragment. Any help?
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
brojStranica.setText(String.valueOf(position + 1) + "/" + String.valueOf(Static.katalozi.getSlikeKataloga().size()));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

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;
}
}

How can i getCurrentView by position in a ViewPager?

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

Categories

Resources