com.giangnvt.fragment.FlashcardPagerFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.giangnvt.fragment.FlashcardPagerFragment.java

Source

/*
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.giangnvt.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.giangnvt.R;
import com.giangnvt.activity.MainActivity;
import com.giangnvt.model.ActionBarMode;
import com.giangnvt.utility.Constant;
import com.giangnvt.utility.FileUtil;
import com.giangnvt.utility.PreferenceManager;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Demonstrates a "screen-slide" com.giangnvt.animation using a {@link ViewPager}. Because {@link ViewPager}
 * automatically plays such an com.giangnvt.animation when calling {@link ViewPager#setCurrentItem(int)}, there
 * isn't any com.giangnvt.animation-specific code in this sample.
 *
 * <p>This sample shows a "next" button that advances the user to the next step in a wizard,
 * animating the current screen out (to the left) and the next screen in (from the right). The
 * reverse com.giangnvt.animation is played when the user presses the "previous" button.</p>
 *
 * @see FlashcardFragment
 */
public class FlashcardPagerFragment extends BaseFragment {

    public static final String BUNDLE_FLASHCARD_PREF_KEY = "flashcardPrefKey";
    public static final String BUNDLE_ENTRY_ID_LIST = "entryIdList";
    public static final String BUNDLE_DATA_FILENAME = "dataFilename";
    public static final String BUNDLE_TABLE_NAME = "tableName";
    public static final String BUNDLE_INITIALIZE_FLG = "initializeFlg";

    public static final String BUNDLE_PAGE_INDEX = "pageIndex";
    public static final String BUNDLE_PAGE_TOTAL = "pageTotal";
    public static final String BUNDLE_ENTRY_ID = "entryId";

    String flashcardPrefKey = null;
    ArrayList<String> entryIdList = null;
    String tableName = null;
    String dataFilename = null;
    int startPosition = 0;
    int currentPosition = 0;

    private ViewPager mViewPager;
    private FragmentStatePagerAdapter mPagerAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_flashcard_pager;
    }

    @Override
    public void initViews() {
    }

    @Override
    public String getFragmentTitle() {
        //return getString(R.string.flashcard_title, (currentPosition + 1), entryIdList.size());
        return "TODO";
    }

    @Override
    public void callSwitchActionBarForListFragment() {
        //TODO do nothing: cause problem because this same method is called inside each pager fragment later
        EnumSet<ActionBarMode> enumSet = EnumSet.of(ActionBarMode.FlashcardOption);
        Log.d(Constant.TAG_MAIN,
                this.getClass().getSimpleName() + "[callSwitchActionBarForListFragment] switch to mode:" + enumSet);
        activity.configActionBarItems(enumSet);
    }

    @Override
    public void readFragmentBundle() {
        super.readFragmentBundle();

        Bundle bundle = getArguments();
        if (bundle != null) {
            flashcardPrefKey = bundle.getString(BUNDLE_FLASHCARD_PREF_KEY);
            if (bundle.containsKey(BUNDLE_ENTRY_ID_LIST)) {
                entryIdList = bundle.getStringArrayList(BUNDLE_ENTRY_ID_LIST);
            } else if (bundle.containsKey(BUNDLE_DATA_FILENAME)) {
                dataFilename = bundle.getString(BUNDLE_DATA_FILENAME);
                entryIdList = new ArrayList<>();
                List<Integer> tmpList = FileUtil.readBinaryFileToIntegerList(getContext(), dataFilename);
                // Exclude the index value at list top
                for (int i = Constant.NUMBER_OF_SCROLL_INDEX; i < tmpList.size(); i++) {
                    entryIdList.add(String.valueOf(tmpList.get(i)));
                }
            } else {
                throw new RuntimeException();
            }
            tableName = bundle.getString(BUNDLE_TABLE_NAME);
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (entryIdList == null || entryIdList.size() == 0 || tableName == null)
            return;

        loadPagerContent();
    }

    public void loadPagerContent() {
        final PreferenceManager pm = PreferenceManager.getInstance(getContext());
        Map<String, Object> currentPrefsMap = pm.getFlashcardPreferences(flashcardPrefKey);
        if (currentPrefsMap != null) {
            startPosition = (Integer) currentPrefsMap.get(PreferenceManager.PREF_FLASHCARD_CURRENT_POSITION);
        }

        mViewPager = (ViewPager) getView().findViewById(R.id.pager_flashcard);
        mPagerAdapter = new FlashcardPagerAdapter(fragmentManager);
        mViewPager.setAdapter(mPagerAdapter);
        ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // When changing pages, reset the action bar actions since they are dependent
                // on which page is currently active. An alternative approach is to have each
                // fragment expose actions itself (rather than the activity exposing actions),
                // but for simplicity, the activity provides the actions in this sample.
                //                invalidateOptionsMenu();
                //                activity.setActionBarTitle("Item:" + position);
                //                activity.setActionBarTitle(((BaseFragment) mPagerAdapter.getItem(position)).getFragmentTitle());
                activity.setActionBarTitle((position + 1) + " of " + entryIdList.size());
                currentPosition = position;

                Map<String, Object> prefsMap = new HashMap<String, Object>();
                prefsMap.put(PreferenceManager.PREF_FLASHCARD_CURRENT_POSITION, currentPosition);

                pm.setFlashcardPreferences(flashcardPrefKey, prefsMap);
            }
        };
        mViewPager.addOnPageChangeListener(pageChangeListener);
        mViewPager.setCurrentItem(startPosition);
        pageChangeListener.onPageSelected(startPosition);
    }

    @Override
    public void configActionbarButtons() {
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity) activity).openFlashcardOptionActivity(flashcardPrefKey,
                        dataFilename == null ? entryIdList : null, dataFilename == null ? null : dataFilename,
                        tableName, false);
            }
        };

        Button flashcardOptionButton = (Button) activity.findViewById(R.id.button_actionbar_flashcard_option);
        ImageView flashcardOptionImage = (ImageView) activity
                .findViewById(R.id.imageview_actionbar_flashcard_option);
        flashcardOptionButton.setOnClickListener(clickListener);
        flashcardOptionImage.setOnClickListener(clickListener);
    }

    @Override
    public void resetLayout() {

    }

    /**
     * A simple pager adapter that represents fragment of type {@link FlashcardFragment} objects.
     */
    private class FlashcardPagerAdapter extends FragmentStatePagerAdapter {
        Fragment currentFragment = null;
        int currentPosition = -1;

        public FlashcardPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Bundle mfragmentArgs = new Bundle();
            mfragmentArgs.putInt(FlashcardPagerFragment.BUNDLE_PAGE_INDEX, position);
            mfragmentArgs.putInt(FlashcardPagerFragment.BUNDLE_PAGE_TOTAL, entryIdList.size());
            mfragmentArgs.putString(FlashcardPagerFragment.BUNDLE_ENTRY_ID, entryIdList.get(position));
            mfragmentArgs.putString(FlashcardPagerFragment.BUNDLE_TABLE_NAME, tableName);
            mfragmentArgs.putString(FlashcardPagerFragment.BUNDLE_FLASHCARD_PREF_KEY, flashcardPrefKey);

            FlashcardFragment fragment = (FlashcardFragment) FlashcardFragment.instantiate(activity,
                    FlashcardFragment.class.getName(), mfragmentArgs);

            currentFragment = fragment;
            currentPosition = position;

            return fragment;
        }

        @Override
        public int getCount() {
            return entryIdList.size();
        }
    }
}