Search in sources :

Example 96 with PagerAdapter

use of android.support.v4.view.PagerAdapter in project android-menudrawer by SimonVT.

the class ViewPagerSample method onCreate.

@Override
protected void onCreate(Bundle inState) {
    super.onCreate(inState);
    mMenuDrawer.setContentView(R.layout.activity_viewpagersample);
    mMenuDrawer.setSlideDrawable(R.drawable.ic_drawer);
    mMenuDrawer.setDrawerIndicatorEnabled(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }
    mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_FULLSCREEN);
    mMenuDrawer.setOnInterceptMoveEventListener(new MenuDrawer.OnInterceptMoveEventListener() {

        @Override
        public boolean isViewDraggable(View v, int dx, int x, int y) {
            if (v == mViewPager) {
                return !(mPagerPosition == 0 && mPagerOffsetPixels == 0) || dx < 0;
            }
            return false;
        }
    });
    mViewPager = (ViewPager) findViewById(R.id.view_pager);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            mPagerPosition = position;
            mPagerOffsetPixels = positionOffsetPixels;
        }
    });
    mPagerAdapter = new PagerAdapter(this);
    mPagerAdapter.addTab(TextViewFragment.class, null);
    mPagerAdapter.addTab(TextViewFragment.class, null);
    mPagerAdapter.addTab(TextViewFragment.class, null);
    mViewPager.setAdapter(mPagerAdapter);
}
Also used : TextView(android.widget.TextView) View(android.view.View) ViewPager(android.support.v4.view.ViewPager) FragmentPagerAdapter(android.support.v4.app.FragmentPagerAdapter) MenuDrawer(net.simonvt.menudrawer.MenuDrawer)

Example 97 with PagerAdapter

use of android.support.v4.view.PagerAdapter in project storymaker by StoryMaker.

the class HomeActivity method initActivityList.

public void initActivityList() {
    // menu items now locked during downloads, i think this can be removed
    /*
        if (!DownloadHelper.checkAllFiles(this)) { // FIXME the app should define these, not the library
            Toast.makeText(this, "Please wait for the content pack to finish downloading and reload the app", Toast.LENGTH_LONG).show(); // FIXME move to strings.xml
            return;
        }
        */
    JsonHelper.setupFileStructure(this);
    // NEW: load instance index
    String lang = StoryMakerApp.getCurrentLocale().getLanguage();
    Timber.d("lang returned from getCurrentLocale: " + lang);
    HashMap<String, InstanceIndexItem> instanceIndex = StorymakerIndexManager.fillInstanceIndex(HomeActivity.this, StorymakerIndexManager.loadInstanceIndex(HomeActivity.this, instanceIndexItemDao), lang, instanceIndexItemDao);
    boolean fileAddedFlag = StorymakerIndexManager.fillInstalledIndex(HomeActivity.this, StorymakerIndexManager.loadInstalledFileIndex(HomeActivity.this, installedIndexItemDao), StorymakerIndexManager.loadAvailableFileIndex(HomeActivity.this, availableIndexItemDao), lang, installedIndexItemDao);
    if (fileAddedFlag) {
        Timber.d("HomeActivity", "file added");
    }
    // FIXME --- this should only happen on app updates in a migration
    if (instanceIndex.size() > 0) {
        Timber.d("INITACTIVITYLIST - FOUND INSTANCE INDEX WITH " + instanceIndex.size() + " ITEMS");
    // dumb test
    // put in values
    /*
            for (InstanceIndexItem item : instanceIndex.values()) {
                instanceIndexItemDao.addInstanceIndexItem(item);
            }

            // read out values
            instanceIndexItemDao.getInstanceIndexItems().subscribe(new Action1<List<org.storymaker.app.db.InstanceIndexItem>>() {

                @Override
                public void call(List<org.storymaker.app.db.InstanceIndexItem> instanceIndexItems) {

                    // just process the list

                    for (org.storymaker.app.db.InstanceIndexItem item : instanceIndexItems) {
                        Timber.d("GOT ITEM " + item.getId() + ", TITLE: " + item.getTitle());
                    }
                }
            });
            */
    } else {
        Timber.d("INITACTIVITYLIST - FOUND INSTANCE INDEX WITH NO ITEMS");
    }
    ArrayList<BaseIndexItem> instances = new ArrayList<BaseIndexItem>(instanceIndex.values());
    ArrayList<BaseIndexItem> installations = new ArrayList<BaseIndexItem>();
    ArrayList<BaseIndexItem> guides = new ArrayList<BaseIndexItem>();
    ArrayList<BaseIndexItem> lessons = new ArrayList<BaseIndexItem>();
    ArrayList<BaseIndexItem> templates = new ArrayList<BaseIndexItem>();
    ArrayList<BaseIndexItem> homeitems = new ArrayList<BaseIndexItem>();
    //HashMap<String, ExpansionIndexItem> availableIds = StorymakerIndexManager.loadAvailableIdIndex(this, availableIndexItemDao);
    //ArrayList<String> availableGuideIds = getIndexItemIdsByType(availableIndexItemDao, "guide");
    //ArrayList<String> availableLessonIds = getIndexItemIdsByType(availableIndexItemDao, "lesson");
    //ArrayList<String> availableTemplateIds = getIndexItemIdsByType(availableIndexItemDao, "template");
    //HashMap<String, ExpansionIndexItem> installedIds = StorymakerIndexManager.loadInstalledIdIndex(this, installedIndexItemDao);
    //ArrayList<String> installedIdList = StorymakerIndexManager.loadInstalledIdIndexList(this, installedIndexItemDao);
    StorymakerIndexManager.IndexKeyMap installedIndexKeyMap = StorymakerIndexManager.loadInstalledIdIndexKeyMap(this, installedIndexItemDao);
    HashMap<String, scal.io.liger.model.sqlbrite.ExpansionIndexItem> installedIds = installedIndexKeyMap.getIndexMap();
    ArrayList<String> installedKeys = installedIndexKeyMap.getIndexKeys();
    ArrayList<String> installedGuideIds = getIndexItemIdsByType(installedIds, "guide");
    ArrayList<String> installedLessonIds = getIndexItemIdsByType(installedIds, "lesson");
    ArrayList<String> installedTemplateIds = getIndexItemIdsByType(installedIds, "template");
    for (String id : installedKeys) {
        // we don't want to populate the home screen with anything that hasn't finished downloading
        InstalledIndexItem checkItem = (InstalledIndexItem) installedIds.get(id);
        if (checkItem.isInstalled()) {
            // if the available item has been installed, add the corresponding item from the installed index
            installations.add(installedIds.get(id));
            if (installedGuideIds.contains(id)) {
                guides.add(checkItem);
            } else if (installedLessonIds.contains(id)) {
                lessons.add(checkItem);
            } else if (installedTemplateIds.contains(id)) {
                templates.add(checkItem);
            }
        } else {
            Timber.d("HomeActivity - " + checkItem.getExpansionId() + " has not finished downloading, it will be skipped");
        }
    }
    // FIXME we should sort this down a layer, perhaps in loadInstanceIndexAsList
    Collections.sort(instances, Collections.reverseOrder());
    // FIXME we should sort this down a layer, perhaps in loadInstanceIndexAsList
    Collections.sort(lessons, Collections.reverseOrder());
    // FIXME we should sort this down a layer, perhaps in loadInstanceIndexAsList
    Collections.sort(guides, Collections.reverseOrder());
    // FIXME we should sort this down a layer, perhaps in loadInstanceIndexAsList
    Collections.sort(templates, Collections.reverseOrder());
    // FIXME we should sort this down a layer, perhaps in loadInstanceIndexAsList
    Collections.sort(installations, Collections.reverseOrder());
    mHomeTabInstanceCount = 0;
    mHomeTabInstallationCount = 0;
    for (int i = 0; i < instances.size(); i++) {
        //System.out.println(list.get(i));
        homeitems.add(instances.get(i));
        mHomeTabInstanceCount++;
        if (i == 1) {
            break;
        }
    }
    if (installations.size() > 0) {
        homeitems.add(installations.get(0));
        mHomeTabInstallationCount++;
    }
    //mRecyclerView.setAdapter(new InstanceIndexItemAdapter(instances, new InstanceIndexItemAdapter.BaseIndexItemSelectedListener() {
    InstanceIndexItemAdapter.BaseIndexItemSelectedListener myBaseIndexItemSelectedListener = new InstanceIndexItemAdapter.BaseIndexItemSelectedListener() {

        @Override
        public void onStorySelected(BaseIndexItem selectedItem) {
            if (selectedItem instanceof InstanceIndexItem) {
                updateInstanceIndexItemLastOpenedDate((InstanceIndexItem) selectedItem);
                launchLiger(HomeActivity.this, null, ((InstanceIndexItem) selectedItem).getInstanceFilePath(), null);
            } else {
                // get clicked item
                final ExpansionIndexItem eItem = ((ExpansionIndexItem) selectedItem);
                Timber.d("HomeActivity - clicked an item: " + eItem.getExpansionId());
                // get installed items
                final HashMap<String, ExpansionIndexItem> installedIds = StorymakerIndexManager.loadInstalledIdIndex(HomeActivity.this, installedIndexItemDao);
                if (!installedIds.containsKey(eItem.getExpansionId())) {
                    // this state should be unreachable, not sure what to do here
                    Timber.e("HomeActivity - " + eItem.getExpansionId() + " was not found in the installed index, something went wrong");
                } else {
                    // proceed as usual
                    Timber.d("HomeActivity - handle click for item: " + eItem.getExpansionId());
                    handleClick(eItem, installedIds, true);
                }
            }
        }
    };
    myHomeItemsInstanceIndexItemAdapter = new InstanceIndexItemAdapter(homeitems, myBaseIndexItemSelectedListener, installedIndexItemDao, instanceIndexItemDao);
    myInstancesInstanceIndexItemAdapter = new InstanceIndexItemAdapter(instances, myBaseIndexItemSelectedListener, installedIndexItemDao, instanceIndexItemDao);
    myGuidesInstanceIndexItemAdapter = new InstanceIndexItemAdapter(guides, myBaseIndexItemSelectedListener, installedIndexItemDao, instanceIndexItemDao);
    myLessonsInstanceIndexItemAdapter = new InstanceIndexItemAdapter(lessons, myBaseIndexItemSelectedListener, installedIndexItemDao, instanceIndexItemDao);
    myTemplatesInstanceIndexItemAdapter = new InstanceIndexItemAdapter(templates, myBaseIndexItemSelectedListener, installedIndexItemDao, instanceIndexItemDao);
    ArrayList<InstanceIndexItemAdapter> myInstanceIndexItemAdapters = new ArrayList<InstanceIndexItemAdapter>();
    myInstanceIndexItemAdapters.add(myHomeItemsInstanceIndexItemAdapter);
    myInstanceIndexItemAdapters.add(myInstancesInstanceIndexItemAdapter);
    myInstanceIndexItemAdapters.add(myGuidesInstanceIndexItemAdapter);
    myInstanceIndexItemAdapters.add(myLessonsInstanceIndexItemAdapter);
    myInstanceIndexItemAdapters.add(myTemplatesInstanceIndexItemAdapter);
    ArrayList<Integer> myListLengths = new ArrayList<Integer>();
    myListLengths.add(homeitems.size());
    myListLengths.add(instances.size());
    myListLengths.add(guides.size());
    myListLengths.add(lessons.size());
    myListLengths.add(templates.size());
    ArrayList<String> myListNames = new ArrayList<String>();
    myListNames.add("home");
    myListNames.add("stories");
    myListNames.add("guides");
    myListNames.add("lessons");
    myListNames.add("templates");
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager(), myInstanceIndexItemAdapters, myListLengths, myListNames, mHomeTabInstanceCount, mHomeTabInstallationCount);
    // Set up the ViewPager with the sections adapter.
    //mViewPager = (SwipelessViewPager) findViewById(R.id.pager);
    mViewPager = (ViewPager) findViewById(R.id.home_pager);
    mViewPager.setAdapter(mDemoCollectionPagerAdapter);
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            currentPage = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
    });
    //mViewPager.setPagingEnabled(false);
    // Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
    // it's PagerAdapter set.
    mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.home_sliding_tabs);
    mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.white));
    //mSlidingTabLayout.setDistributeEvenly(true);
    mSlidingTabLayout.setViewPager(mViewPager);
    if (currentPage != -1) {
        mViewPager.setCurrentItem(currentPage);
    }
//} else {
// empty list
//    TextView textView = (TextView) findViewById(R.id.textViewEmptyState);
//    textView.setVisibility(View.VISIBLE);
//mSwipeRefreshLayout.setVisibility(View.GONE);
//}
}
Also used : ArrayList(java.util.ArrayList) ExpansionIndexItem(scal.io.liger.model.sqlbrite.ExpansionIndexItem) InstalledIndexItem(scal.io.liger.model.sqlbrite.InstalledIndexItem) BaseIndexItem(scal.io.liger.model.sqlbrite.BaseIndexItem) InstanceIndexItem(scal.io.liger.model.sqlbrite.InstanceIndexItem) StorymakerIndexManager(scal.io.liger.StorymakerIndexManager) ViewPager(android.support.v4.view.ViewPager)

Example 98 with PagerAdapter

use of android.support.v4.view.PagerAdapter in project Reader by TheKeeperOfPie.

the class FragmentNewMessage method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_new_message, container, false);
    layoutCoordinator = (CoordinatorLayout) view.findViewById(R.id.layout_coordinator);
    layoutAppBar = (AppBarLayout) view.findViewById(R.id.layout_app_bar);
    scrollText = (NestedScrollView) view.findViewById(R.id.scroll_text);
    textAuthor = (TextView) view.findViewById(R.id.text_author);
    textAuthor.setText(getString(R.string.sending_from) + " " + controllerUser.getUser().getName());
    editTextRecipient = (EditText) view.findViewById(R.id.edit_recipient);
    editTextSubject = (EditText) view.findViewById(R.id.edit_subject);
    editTextMessage = (EditText) view.findViewById(R.id.edit_message);
    Bundle arguments = getArguments();
    editTextRecipient.setText(arguments.getString(ARG_RECIPIENT));
    editTextSubject.setText(arguments.getString(ARG_SUBJECT));
    editTextMessage.setText(arguments.getString(ARG_MESSAGE));
    toolbar = (Toolbar) view.findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.message));
    toolbar.setTitleTextColor(themer.getColorFilterPrimary().getColor());
    toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
    toolbar.setNavigationOnClickListener(v -> {
        UtilsInput.hideKeyboard(editTextMessage);
        mListener.onNavigationBackClick();
    });
    toolbar.getNavigationIcon().mutate().setColorFilter(themer.getColorFilterPrimary());
    setUpOptionsMenu();
    View.OnFocusChangeListener onFocusChangeListener = (v, hasFocus) -> {
        if (hasFocus) {
            AppBarLayout.Behavior behaviorAppBar = (AppBarLayout.Behavior) ((CoordinatorLayout.LayoutParams) layoutAppBar.getLayoutParams()).getBehavior();
            behaviorAppBar.onNestedFling(layoutCoordinator, layoutAppBar, null, 0, 1000, true);
        }
    };
    editTextRecipient.setOnFocusChangeListener(onFocusChangeListener);
    editTextSubject.setOnFocusChangeListener(onFocusChangeListener);
    editTextMessage.setOnFocusChangeListener(onFocusChangeListener);
    editMarginDefault = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
    editMarginWithActions = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 56, getResources().getDisplayMetrics());
    textPreview = (TextView) view.findViewById(R.id.text_preview);
    viewDivider = view.findViewById(R.id.view_divider);
    toolbarActions = (Toolbar) view.findViewById(R.id.toolbar_actions);
    toolbarActions.inflateMenu(R.menu.menu_editor_actions);
    toolbarActions.setOnMenuItemClickListener(this);
    tabLayout = (TabLayout) view.findViewById(R.id.layout_tab);
    tabLayout.setTabMode(TabLayout.MODE_FIXED);
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setTabTextColors(themer.getColorFilterTextMuted().getColor(), themer.getColorFilterPrimary().getColor());
    viewPager = (ViewPager) view.findViewById(R.id.view_pager);
    viewPager.setAdapter(new PagerAdapter() {

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position) {
                case PAGE_BODY:
                    return getString(R.string.page_message);
                case PAGE_PREVIEW:
                    return getString(R.string.page_preview);
            }
            return super.getPageTitle(position);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return viewPager.getChildAt(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
        }

        @Override
        public int getCount() {
            return viewPager.getChildCount();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    });
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if (position == PAGE_BODY && toolbarActions.getVisibility() == View.VISIBLE) {
                float translationY = positionOffset * (toolbarActions.getHeight() + viewDivider.getHeight());
                viewDivider.setTranslationY(translationY);
                toolbarActions.setTranslationY(translationY);
            }
        }

        @Override
        public void onPageSelected(int position) {
            if (position == PAGE_PREVIEW) {
                if (editTextMessage.length() == 0) {
                    textPreview.setText(R.string.empty_reply_preview);
                } else {
                    textPreview.setText(Html.fromHtml(Processor.process(editTextMessage.getText().toString())));
                }
            }
            itemHideActions.setVisible(position == PAGE_BODY);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
    tabLayout.setupWithViewPager(viewPager);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    layoutCaptcha = (RelativeLayout) view.findViewById(R.id.layout_captcha);
    imageCaptcha = (ImageView) view.findViewById(R.id.image_captcha);
    editCaptcha = (EditText) view.findViewById(R.id.edit_captcha);
    buttonCaptchaRefresh = (ImageButton) view.findViewById(R.id.button_captcha_refresh);
    buttonCaptchaRefresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            loadCaptcha();
        }
    });
    reddit.needsCaptcha().subscribe(new Observer<String>() {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
        }

        @Override
        public void onNext(String response) {
            Log.d(TAG, "needsCaptcha onNext: " + response);
            if ("true".equalsIgnoreCase(response)) {
                layoutCaptcha.setVisibility(View.VISIBLE);
                loadCaptcha();
            }
        }
    });
    view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            Menu menu = toolbarActions.getMenu();
            int maxNum = (int) (view.getWidth() / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, getResources().getDisplayMetrics()));
            int numShown = 0;
            for (int index = 0; index < menu.size(); index++) {
                MenuItem menuItem = menu.getItem(index);
                menuItem.getIcon().setColorFilter(themer.getColorFilterIcon());
                if (numShown++ < maxNum - 1) {
                    menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                } else {
                    menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
                }
            }
            // Toggle visibility to fix weird bug causing tabs to not be added
            tabLayout.setVisibility(View.GONE);
            tabLayout.setVisibility(View.VISIBLE);
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
    return view;
}
Also used : AppBarLayout(android.support.design.widget.AppBarLayout) CoordinatorLayout(android.support.design.widget.CoordinatorLayout) ImageButton(android.widget.ImageButton) Bundle(android.os.Bundle) ImageView(android.widget.ImageView) ViewPager(android.support.v4.view.ViewPager) MenuItem(android.view.MenuItem) TabLayout(android.support.design.widget.TabLayout) Inject(javax.inject.Inject) Picasso(com.squareup.picasso.Picasso) JSONException(org.json.JSONException) Reddit(com.winsonchiu.reader.data.reddit.Reddit) JSONObject(org.json.JSONObject) Toast(android.widget.Toast) Menu(android.view.Menu) View(android.view.View) NestedScrollView(android.support.v4.widget.NestedScrollView) Log(android.util.Log) Processor(com.github.rjeschke.txtmark.Processor) UtilsInput(com.winsonchiu.reader.utils.UtilsInput) LayoutInflater(android.view.LayoutInflater) PagerAdapter(android.support.v4.view.PagerAdapter) TextUtils(android.text.TextUtils) Observer(rx.Observer) ViewGroup(android.view.ViewGroup) TextView(android.widget.TextView) TypedValue(android.util.TypedValue) Toolbar(android.support.v7.widget.Toolbar) Html(android.text.Html) ViewTreeObserver(android.view.ViewTreeObserver) RelativeLayout(android.widget.RelativeLayout) Nullable(android.support.annotation.Nullable) Activity(android.app.Activity) EditText(android.widget.EditText) PagerAdapter(android.support.v4.view.PagerAdapter) TabLayout(android.support.design.widget.TabLayout) AppBarLayout(android.support.design.widget.AppBarLayout) Menu(android.view.Menu) ViewTreeObserver(android.view.ViewTreeObserver) Bundle(android.os.Bundle) ViewGroup(android.view.ViewGroup) MenuItem(android.view.MenuItem) ImageView(android.widget.ImageView) View(android.view.View) NestedScrollView(android.support.v4.widget.NestedScrollView) TextView(android.widget.TextView) ViewPager(android.support.v4.view.ViewPager) JSONObject(org.json.JSONObject)

Example 99 with PagerAdapter

use of android.support.v4.view.PagerAdapter in project android-auto-scroll-view-pager by Trinea.

the class AutoScrollViewPager method scrollOnce.

/**
     * scroll only once
     */
public void scrollOnce() {
    PagerAdapter adapter = getAdapter();
    int currentItem = getCurrentItem();
    int totalCount;
    if (adapter == null || (totalCount = adapter.getCount()) <= 1) {
        return;
    }
    int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;
    if (nextItem < 0) {
        if (isCycle) {
            setCurrentItem(totalCount - 1, isBorderAnimation);
        }
    } else if (nextItem == totalCount) {
        if (isCycle) {
            setCurrentItem(0, isBorderAnimation);
        }
    } else {
        setCurrentItem(nextItem, true);
    }
}
Also used : PagerAdapter(android.support.v4.view.PagerAdapter)

Example 100 with PagerAdapter

use of android.support.v4.view.PagerAdapter in project android-auto-scroll-view-pager by Trinea.

the class AutoScrollViewPager method dispatchTouchEvent.

/**
     * <ul>
     * if stopScrollWhenTouch is true
     * <li>if event is down, stop auto scroll.</li>
     * <li>if event is up, start auto scroll again.</li>
     * </ul>
     */
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    int action = MotionEventCompat.getActionMasked(ev);
    if (stopScrollWhenTouch) {
        if ((action == MotionEvent.ACTION_DOWN) && isAutoScroll) {
            isStopByTouch = true;
            stopAutoScroll();
        } else if (ev.getAction() == MotionEvent.ACTION_UP && isStopByTouch) {
            startAutoScroll();
        }
    }
    if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT || slideBorderMode == SLIDE_BORDER_MODE_CYCLE) {
        touchX = ev.getX();
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            downX = touchX;
        }
        int currentItem = getCurrentItem();
        PagerAdapter adapter = getAdapter();
        int pageCount = adapter == null ? 0 : adapter.getCount();
        /**
             * current index is first one and slide to right or current index is last one and slide to left.<br/>
             * if slide border mode is to parent, then requestDisallowInterceptTouchEvent false.<br/>
             * else scroll to last one when current item is first one, scroll to first one when current item is last
             * one.
             */
        if ((currentItem == 0 && downX <= touchX) || (currentItem == pageCount - 1 && downX >= touchX)) {
            if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT) {
                getParent().requestDisallowInterceptTouchEvent(false);
            } else {
                if (pageCount > 1) {
                    setCurrentItem(pageCount - currentItem - 1, isBorderAnimation);
                }
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.dispatchTouchEvent(ev);
        }
    }
    getParent().requestDisallowInterceptTouchEvent(true);
    return super.dispatchTouchEvent(ev);
}
Also used : PagerAdapter(android.support.v4.view.PagerAdapter)

Aggregations

PagerAdapter (android.support.v4.view.PagerAdapter)111 View (android.view.View)47 ViewPager (android.support.v4.view.ViewPager)39 TextView (android.widget.TextView)33 HorizontalScrollView (android.widget.HorizontalScrollView)19 ViewGroup (android.view.ViewGroup)18 LinearLayout (android.widget.LinearLayout)13 Toolbar (android.support.v7.widget.Toolbar)11 ImageView (android.widget.ImageView)11 TabLayout (android.support.design.widget.TabLayout)8 RecyclerView (android.support.v7.widget.RecyclerView)8 ArrayList (java.util.ArrayList)8 FragmentPagerAdapter (android.support.v4.app.FragmentPagerAdapter)6 AppBarLayout (android.support.design.widget.AppBarLayout)5 CoordinatorLayout (android.support.design.widget.CoordinatorLayout)5 FragmentStatePagerAdapter (android.support.v4.app.FragmentStatePagerAdapter)5 ImageButton (android.widget.ImageButton)5 LargeTest (android.support.test.filters.LargeTest)4 MediumTest (android.support.test.filters.MediumTest)4 SmallTest (android.support.test.filters.SmallTest)4