com.google.samples.apps.topeka.view.quiz.QuizFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.google.samples.apps.topeka.view.quiz.QuizFragment.java

Source

/*
 * Copyright 2015 Google Inc.
 *
 * 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.google.samples.apps.topeka.view.quiz;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterViewAnimator;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.samples.apps.topeka.R;
import com.google.samples.apps.topeka.helper.ApiLevelHelper;
import com.google.samples.apps.topeka.model.Avatar;
import com.google.samples.apps.topeka.model.Category;
import com.google.samples.apps.topeka.model.Theme;
import com.google.samples.apps.topeka.widget.AvatarView;
import com.google.samples.apps.topeka.widget.quiz.AbsQuizView;

/**
 * Encapsulates Quiz solving and displays it to the user.
 */
public class QuizFragment extends android.support.v4.app.Fragment {

    private static final String KEY_USER_INPUT = "USER_INPUT";
    private static final String KEY_THEME = "THEME";
    private TextView mProgressText;

    private ProgressBar mProgressBar;

    private AdapterViewAnimator mQuizView;
    private ScoreAdapter mScoreAdapter;
    private QuizAdapter mQuizAdapter;
    private AvatarView avatar;
    private FragmentViewCreatedListener lifecycleListener;

    public static QuizFragment newInstance(Theme theme, FragmentViewCreatedListener lifecycleListener) {

        Bundle args = new Bundle();
        args.putSerializable(KEY_THEME, theme);
        QuizFragment fragment = new QuizFragment();
        fragment.setArguments(args);
        fragment.lifecycleListener = lifecycleListener;
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        // Create a themed Context and custom LayoutInflater
        // to get nicely themed views in this Fragment.
        final Theme theme = (Theme) getArguments().getSerializable(KEY_THEME);
        final ContextThemeWrapper context = new ContextThemeWrapper(getActivity(), theme.getStyleId());
        final LayoutInflater themedInflater = LayoutInflater.from(context);
        return themedInflater.inflate(R.layout.fragment_quiz, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mQuizView = (AdapterViewAnimator) view.findViewById(R.id.quiz_view);
        setQuizViewAnimations();

        this.avatar = (AvatarView) view.findViewById(R.id.avatar);
        mProgressText = (TextView) view.findViewById(R.id.progress_text);
        mProgressBar = ((ProgressBar) view.findViewById(R.id.progress));

        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        if (lifecycleListener != null) {
            lifecycleListener.onQuizViewRendered();
        }
        super.onResume();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void setQuizViewAnimations() {
        if (ApiLevelHelper.isLowerThan(Build.VERSION_CODES.LOLLIPOP)) {
            return;
        }
        mQuizView.setInAnimation(getActivity(), R.animator.slide_in_bottom);
        mQuizView.setOutAnimation(getActivity(), R.animator.slide_out_top);
    }

    public void loadQuizView(Category category, int quizPosition) {
        mQuizView.setAdapter(getQuizAdapter(category));
        mQuizView.setSelection(quizPosition);
    }

    private QuizAdapter getQuizAdapter(Category category) {
        if (null == mQuizAdapter) {
            mQuizAdapter = new QuizAdapter(getActivity(), category);
        }
        return mQuizAdapter;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        View focusedChild = mQuizView.getFocusedChild();
        if (focusedChild instanceof ViewGroup) {
            View currentView = ((ViewGroup) focusedChild).getChildAt(0);
            if (currentView instanceof AbsQuizView) {
                outState.putBundle(KEY_USER_INPUT, ((AbsQuizView) currentView).getUserInput());
            }
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onViewStateRestored(Bundle savedInstanceState) {
        restoreQuizState(savedInstanceState);
        super.onViewStateRestored(savedInstanceState);
    }

    private void restoreQuizState(final Bundle savedInstanceState) {
        if (null == savedInstanceState) {
            return;
        }
        mQuizView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
                    int oldRight, int oldBottom) {
                mQuizView.removeOnLayoutChangeListener(this);
                View currentChild = mQuizView.getChildAt(0);
                if (currentChild instanceof ViewGroup) {
                    final View potentialQuizView = ((ViewGroup) currentChild).getChildAt(0);
                    if (potentialQuizView instanceof AbsQuizView) {
                        ((AbsQuizView) potentialQuizView)
                                .setUserInput(savedInstanceState.getBundle(KEY_USER_INPUT));
                    }
                }
            }
        });

    }

    public void showNextQuizPage() {
        if (null == mQuizView) {
            return;
        }
        mQuizView.showNext();
    }

    public void showSummary(Category category) {
        @SuppressWarnings("ConstantConditions")
        final ListView scorecardView = (ListView) getView().findViewById(R.id.scorecard);
        mScoreAdapter = getScoreAdapter(category);
        scorecardView.setAdapter(mScoreAdapter);
        scorecardView.setVisibility(View.VISIBLE);
        mQuizView.setVisibility(View.GONE);
    }

    private ScoreAdapter getScoreAdapter(Category category) {
        if (null == mScoreAdapter) {
            mScoreAdapter = new ScoreAdapter(category);
        }
        return mScoreAdapter;
    }

    public void displayProgress(int currentQuizPosition, int quizPositionsCount) {
        mProgressText.setText(getString(R.string.quiz_of_quizzes, currentQuizPosition, quizPositionsCount));
        mProgressBar.setMax(quizPositionsCount);
        mProgressBar.setProgress(currentQuizPosition);
    }

    public void displayAvatar(Avatar avatar) {
        this.avatar.setAvatar(avatar.getDrawableId());
        ViewCompat.animate(this.avatar).setInterpolator(new FastOutLinearInInterpolator()).setStartDelay(500)
                .scaleX(1).scaleY(1).start();
    }

    public interface FragmentViewCreatedListener {
        void onQuizViewRendered();
    }

}