Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

infinite gallery scrolling with determined image position

One of my app activity is called DayGallery activity (infinite images gallery) ,

when i open the gallery, it show first image randomly , and not start with first image i specified in DayGallery activity code .

what am trying to achieve is:

FIRST: start with first image specified in DayGallery activity code as below :

when open Day1 gallery ,first image to appear is:

R.drawable.day_one_1

and when open Day2 gallery ,first image to appear is:

R.drawable.day_two_1

and like that for all Days gallery, also keep infinite scrolling in both sides.

SECOND : if am in gallery stopped on image named day_one_7 for example then press back to go to previous activity and return again to gallery , i want to see the same image i saw before i left gallery , but if i exit the app then open the gallery again , it must reset to show the first image i specified in DayGallery activity code , explained as bellow image .

enter image description here

actually i searched google for that purpose but i cant get any helpful thing about it ,

any help will be highly appreciated .

DayGallery.java:

 @SuppressWarnings("deprecation")
public class DayGallery extends Activity {
TextView tv;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
            WindowManager.LayoutParams.FLAG_FULLSCREEN);  
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    Boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
    // Set the layout to use
    setContentView(R.layout.main);
    if (customTitleSupported) { 
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title); 
         tv = (TextView) findViewById(R.id.title_tv1); 
         tv.setTypeface(FontFactory.getBFantezy(getBaseContext()));
         }           
    InfiniteGallery galleryOne = (InfiniteGallery) findViewById(R.id.galleryOne);
    galleryOne.setAdapter(initializeImages()); 
    galleryOne.setSelection(galleryOne.getCount()/2);  
    }  

private InfiniteGalleryAdapter initializeImages() {
    InfiniteGalleryAdapter galleryAdapter = null;

    String day = getIntent().getStringExtra("dayname");

    if(day.equalsIgnoreCase("Day1")){
        int[] tempimages = { R.drawable.day_one_1, R.drawable.day_one_2,R.drawable.day_one_3, 
                R.drawable.day_one_4, R.drawable.day_one_5,R.drawable.day_one_6,R.drawable.day_one_7,       
                R.drawable.day_one_8, R.drawable.day_one_9,R.drawable.day_one_10,R.drawable.day_one_11,
                R.drawable.day_one_12
        };  
        String[] name = { "00:35","00:35","00:35","1:07","2:00","2:01","2:09",
                          "2:12","2:15","6:13","6:13","6:13"
        };  
        tv.setText("Day one pictures");
        galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name); 
        }       
    else if(day.equalsIgnoreCase("Day2")){
        int[] tempimages = { R.drawable.day_two_1, R.drawable.day_two_2,R.drawable.day_two_3, 
                R.drawable.day_two_4, R.drawable.day_two_5,R.drawable.day_two_6,R.drawable.day_two_7,
                R.drawable.day_two_8, R.drawable.day_two_9,R.drawable.day_two_10,R.drawable.day_two_11,
                R.drawable.day_two_12
        };  
        String[] name = { "12:04","12:04", "12:04","12:05","12:06", "12:07",
                          "12:07","12:07","12:08","12:10","12:10","12:10"
        };  
        tv.setText("Day two pictures"); 
        galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name); 
        }

    // AND THE SAME FOR REST OF DAYS TILL Day10//

    return galleryAdapter; 
    }
}

 class InfiniteGalleryAdapter extends BaseAdapter { 
private Context mContext;
private int[] images;   
private String[] name;
public InfiniteGalleryAdapter(Context c, int[] imageIds,String[] names) { 
    this.mContext = c; 
    images = imageIds;
    name=names;
    inflater = (LayoutInflater)mContext.getSystemService ( Context.LAYOUT_INFLATER_SERVICE); 
    } 
public int getCount() { 
    return Integer.MAX_VALUE; 
    } 
public Object getItem(int position) { 
    return position; 
    } 
public long getItemId(int position) { 
    return position; 
    } 
private LayoutInflater inflater=null; 

public class ViewHolder{ 
    public TextView text; 
    public ImageView image; 
    } 

public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView i = getImageView(); 

    int itemPos = (position % images.length); 

    try { i.setImageResource(images[itemPos]); ((BitmapDrawable) i.getDrawable()).setAntiAlias(true); 
    } 
    catch (OutOfMemoryError e) { Log.e("InfiniteGalleryAdapter", "Out of memory creating imageview. Using empty view.", e); 
    } 
    View vi=convertView; 
    ViewHolder holder; 
    if(convertView==null){ 
        vi = inflater.inflate(R.layout.gallery_items, null); 
        holder=new ViewHolder(); 
        holder.text=(TextView)vi.findViewById(R.id.textView1); 
        holder.image=(ImageView)vi.findViewById(R.id.image); 
        vi.setTag(holder); 
        } 
    else holder=(ViewHolder)vi.getTag(); 
    holder.text.setText(name[itemPos]); 

    final int stub_id=images[itemPos]; 
    holder.image.setImageResource(stub_id); 

    return vi; 
    } 

private ImageView getImageView() { 

    ImageView i = new ImageView(mContext); 

    return i; 
    } 
}

  @SuppressWarnings("deprecation")
 class InfiniteGallery extends Gallery {

public InfiniteGallery(Context context) {
    super(context);
    init(); 
    }

public InfiniteGallery(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(); 
    }

public InfiniteGallery(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(); 
    }

private void init(){
    // These are just to make it look pretty
    setSpacing(25);
    setHorizontalFadingEdgeEnabled(false); 
    }
}

UPDATE:

I add this line of code :

 galleryOne.setSelection(0);

after this line :

galleryOne.setSelection(galleryOne.getCount()/2);  

in my code it result in showing the first image as specified it in DayGallery activity , but it result to one way infinite scrolling to left side only but not in both side ,

How we can get two way infinite scrolling of my gallery images with showing the first image as specified it in DayGallery activity ?

really appreciate any help , thanks.

like image 737
Android Stack Avatar asked Nov 12 '22 23:11

Android Stack


1 Answers

I can tell you the logic to write infinite viewpager which uses fragments. This viewpager can scroll in both direction infinitely. Also it can be launched from any particular fragment. My requiremnet was:

I had an ebook and user can click on any menu(chapters) and it should launch that and then it should be possible to scroll both ways. I guess your are trying to achieve same thing with gallery:

Check the code:

InfinitePagerAdapter.java:

package com.example.multiplepages;

import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

/**
 * A PagerAdapter that wraps around another PagerAdapter to handle paging
 * wrap-around.
 * 
 */
public class InfinitePagerAdapter extends PagerAdapter {

    private static final String TAG = "InfinitePagerAdapter";
    private static final boolean DEBUG = true;

    private PagerAdapter adapter;

    public InfinitePagerAdapter(PagerAdapter adapter) {
    this.adapter = adapter;
    }

    @Override
    public int getCount() {
    // warning: scrolling to very high values (1,000,000+) results in
    // strange drawing behaviour
    return Integer.MAX_VALUE;

    }

    /**
     * @return the {@link #getCount()} result of the wrapped adapter
     */
    public int getRealCount() {
    return adapter.getCount();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        debug("getRealCount: " + getRealCount());
        int virtualPosition = position % getRealCount();
        debug("instantiateItem: real position: " + position);
        debug("instantiateItem: virtual position: " + virtualPosition);

        // only expose virtual position to the inner adapter
        return adapter.instantiateItem(container, virtualPosition);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    int virtualPosition = position % getRealCount();
    debug("destroyItem: real position: " + position);
    debug("destroyItem: virtual position: " + virtualPosition);

    // only expose virtual position to the inner adapter
    adapter.destroyItem(container, virtualPosition, object);
    }

    /*
     * Delegate rest of methods directly to the inner adapter.
     */

    @Override
    public void finishUpdate(ViewGroup container) {
    adapter.finishUpdate(container);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
    return adapter.isViewFromObject(view, object);
    }

    @Override
    public void restoreState(Parcelable bundle, ClassLoader classLoader) {
    adapter.restoreState(bundle, classLoader);
    }

    @Override
    public Parcelable saveState() {
    return adapter.saveState();
    }

    @Override
    public void startUpdate(ViewGroup container) {
    adapter.startUpdate(container);
    }

    /*
     * End delegation
     */

    private void debug(String message) {
    if (DEBUG) {
        Log.d(TAG, message);
    }
    }
}

InfiniteViewPager.java:

package com.example.multiplepages;


import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;

/**
 * A {@link ViewPager} that allows pseudo-infinite paging with a wrap-around
 * effect. Should be used with an {@link InfinitePagerAdapter}.
 * 
 */
public class InfiniteViewPager extends ViewPager {

    int mPageOffset = 0;

    public InfiniteViewPager(Context context) {
    super(context);
    }

    public InfiniteViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    }

    @Override
    public void setAdapter(PagerAdapter adapter) {
    super.setAdapter(adapter);
    // offset first element so that we can scroll to the left
    setCurrentItem(0);
    }

    public void setpageOffset(int pageOffset) {
        mPageOffset = pageOffset;
    }

   @Override
    public void setCurrentItem(int item) {
    // offset the current item to ensure there is space to scroll
    item = getOffsetAmount() + (item % getAdapter().getCount());
    item = item + mPageOffset;
    super.setCurrentItem(item);

    }

    private int getOffsetAmount() {
    if (getAdapter() instanceof InfinitePagerAdapter) {
        InfinitePagerAdapter infAdapter = (InfinitePagerAdapter) getAdapter();
        // allow for 100 back cycles from the beginning
        // should be enough to create an illusion of infinity
        // warning: scrolling to very high values (1,000,000+) results in
        // strange drawing behaviour
        return infAdapter.getRealCount() * 100;
    } else {
        return 0;
    }
    }

}

MultiplePageScroll.java : This is MainActivity

package com.example.multiplepages;

import java.util.ArrayList;
import java.util.List;

import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.support.v4.app.Fragment;  
import android.support.v4.app.FragmentActivity;  
import android.support.v4.app.FragmentManager;  
import android.support.v4.app.FragmentPagerAdapter;  
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager; 
import android.support.v4.view.ViewPager.OnPageChangeListener;

public class MultiplePageScroll extends FragmentActivity  {

    private int listSize = 0;
    public int listPos = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_multiple_page_scroll);
        Bundle bundle = getIntent().getExtras(); 
        listSize = bundle.getInt("listSize");
        listPos = bundle.getInt("itemPosition");

        PagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
            return listSize;
            }

            @Override
            public Fragment getItem(int position) {
            Fragment fragment = new PageFragment();
            Bundle args = new Bundle();
            args.putInt("identifier", position);
            fragment.setArguments(args);
            return fragment;
            }
        };

        // wrap pager to provide infinite paging with wrap-around
        PagerAdapter wrappedAdapter = new InfinitePagerAdapter(adapter);

        // actually an InfiniteViewPager
        InfiniteViewPager viewPager = (InfiniteViewPager) findViewById(R.id.pager);
        viewPager.setpageOffset(listPos);
        viewPager.setAdapter(wrappedAdapter);

    }
}

PageFragment.java:

package com.example.multiplepages;

import java.io.IOException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;  
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;  
import android.view.MotionEvent;
import android.view.View;  
import android.view.ViewGroup;  
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;  
//import android.webkit.WebSettings;
import android.widget.Toast;


public class PageFragment extends Fragment { 

    String path="s_english/contents";
    AssetManager assMan = null;
    int pageIndex;
    String pagePath = null;    
    String[] pageList = null; 
    private int listPosition;

     public static PageFragment newInstance(int index) {

         PageFragment pageFragment = new PageFragment();
         Bundle bundle = new Bundle();
         bundle.putInt("index", index);
         pageFragment.setArguments(bundle);
         return pageFragment;
     }

     @Override  
     public void onCreate(Bundle savedInstanceState) {  
         super.onCreate(savedInstanceState); 
        Bundle args = getArguments();
        listPosition = args.getInt("identifier");
     }  

     @Override  
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  

         View view = inflater.inflate(R.layout.fragment, container, false);  
         WebView mWebView = (WebView) view.findViewById(R.id.webview);
         mWebView.addJavascriptInterface(new JavaScriptInterface(getActivity()), "NativeFunc");
         WebSettings webSettings = mWebView.getSettings();       
         webSettings.setJavaScriptEnabled(true); 
         mWebView.setWebViewClient(new MyWebViewClient());       
         mWebView.getSettings().setBuiltInZoomControls(true);

         assMan = getActivity().getAssets();
         try {
             pageList = assMan.list(path);
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         pageIndex = listPosition;
         pagePath=pageList[pageIndex];

         mWebView.loadUrl("file:///android_asset/s_english/contents/" + pagePath);
             //mWebView.loadUrl("http://192.168.0.33:8080/orginalsource/contents/" + pagePath);
            //MultiplePageScroll.mSpinner.setVisibility(View.GONE);

         return view;  
     }  

     @Override
     public void onSaveInstanceState(Bundle outState) {
         super.onSaveInstanceState(outState);
         outState.putBoolean("dummy", true);
     }


    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

    }

}  

activity_multiple_page_scroll.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.example.multiplepages.InfiniteViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

You can use sharedPrefernce to save the launchedpage and use that. By modifying this code a little you can achieve what you want.

like image 143
Sushil Avatar answered Nov 15 '22 11:11

Sushil