fr.shywim.antoinedaniel.ui.fragment.VideoListFragment.java Source code

Java tutorial

Introduction

Here is the source code for fr.shywim.antoinedaniel.ui.fragment.VideoListFragment.java

Source

/*
 * Copyright (c) 2015 Matthieu Harl
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package fr.shywim.antoinedaniel.ui.fragment;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.transition.TransitionInflater;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Filter;
import android.widget.FilterQueryProvider;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import fr.shywim.antoinedaniel.R;
import fr.shywim.antoinedaniel.provider.ProviderConstants;
import fr.shywim.antoinedaniel.provider.ProviderContract;
import fr.shywim.antoinedaniel.ui.MainActivity;
import fr.shywim.antoinedaniel.ui.adapter.CursorRecyclerAdapter;
import fr.shywim.antoinedaniel.ui.adapter.VideoListAdapter;
import fr.shywim.antoinedaniel.utils.UiUtils;

public class VideoListFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
    private static final String TAG_VIDEO_DETAILS = "tag_video_details";
    protected static final String ARG_LOADER_WHERE = "where";

    private Context mContext;
    private RecyclerView listView;
    private Toolbar mToolbar;
    private View mStatusBarBg;

    public VideoListFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
        ((FragmentsCallbacks) activity).onFragmentAttached(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        getLoaderManager().initLoader(MainActivity.VIDEOS, null, this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_video_list, container, false);

        listView = (RecyclerView) root.findViewById(R.id.videos_list);
        listView.setAdapter(setupAdapter());
        listView.setLayoutManager(
                new StaggeredGridLayoutManager(getColumnNumber(), StaggeredGridLayoutManager.VERTICAL));
        ((CursorRecyclerAdapter) listView.getAdapter())
                .setOnClickListener(new CursorRecyclerAdapter.OnClickListener() {
                    @Override
                    public void onClick(View v, String videoId, String videoName) {
                        displayDetailsFragment(v, videoId, videoName);
                    }
                });

        mToolbar = (Toolbar) root.findViewById(R.id.toolbar_actionbar);
        mToolbar.setTitle("");
        ((FragmentsCallbacks) mContext).setActionBarToolbar(mToolbar);
        ((View) mToolbar.getParent()).getBackground().setAlpha(255);

        mStatusBarBg = root.findViewById(R.id.statusbar_bg);
        UiUtils.setStatusBarBackground(mStatusBarBg, getResources());

        setupToolbarSpinner((Spinner) root.findViewById(R.id.videos_list_chooser));

        return root;
    }

    private void displayDetailsFragment(View v, String videoId, String videoName) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        Fragment fragment = VideoDetailsFragment.newInstance(videoId, videoName);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setSharedElementReturnTransition(
                    TransitionInflater.from(mContext).inflateTransition(R.transition.simple_image_transition));
            setExitTransition(TransitionInflater.from(mContext).inflateTransition(android.R.transition.fade));
            setReenterTransition(TransitionInflater.from(mContext).inflateTransition(android.R.transition.fade));
            setReturnTransition(TransitionInflater.from(mContext).inflateTransition(android.R.transition.fade));
            fragment.setSharedElementEnterTransition(
                    TransitionInflater.from(mContext).inflateTransition(R.transition.simple_image_transition));
            fragment.setEnterTransition(
                    TransitionInflater.from(mContext).inflateTransition(android.R.transition.fade));
        } else {
            ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out);
        }
        fragment.setAllowEnterTransitionOverlap(true);
        fragment.setAllowReturnTransitionOverlap(true);

        View containerView = getView() != null ? (View) getView().getParent() : null;
        if (containerView != null) {
            ft.replace(containerView.getId(), fragment);
            ft.addToBackStack(TAG_VIDEO_DETAILS);
            ft.addSharedElement(v.findViewById(R.id.playlist_row_image),
                    VideoDetailsFragment.THMB_TRANSITION_NAME + videoId);
            ft.commit();
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.removeGroup(R.id.sound_menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    private int getColumnNumber() {
        Configuration configuration = getResources().getConfiguration();
        return configuration.screenWidthDp / 180;
    }

    private RecyclerView.Adapter setupAdapter() {
        CursorRecyclerAdapter adapter = new VideoListAdapter(mContext);

        adapter.setFilterQueryProvider(new FilterQueryProvider() {
            @Override
            public Cursor runQuery(CharSequence constraint) {
                String where = null;

                if (constraint != null && !TextUtils.isEmpty(constraint)) {
                    where = ProviderContract.VideosEntry.COLUMN_NAME_PAGE + "=\"" + constraint + '"';
                }

                return mContext.getContentResolver().query(ProviderConstants.VIDEOS_URI, null, where, null,
                        ProviderContract.VideosEntry.COLUMN_NAME_TIMESTAMP + " DESC");
            }
        });

        return adapter;
    }

    private void setupToolbarSpinner(Spinner spinner) {
        spinner.setAdapter(new SpinnerAdapter() {
            private static final String TAG_DROPDOWN = "dropdown";
            private static final String TAG_NOT_DROPDOWN = "not_dropdown";

            String[] titles = getResources().getStringArray(R.array.dropdown_videos_list_titles);

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                if (convertView == null || !convertView.getTag().toString().equals(TAG_NOT_DROPDOWN)) {
                    convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.spinner_actionbar_item,
                            parent, false);
                    convertView.setTag(TAG_NOT_DROPDOWN);
                }
                if (position != 0) {
                    convertView.findViewById(R.id.divider_view).setVisibility(View.GONE);
                } else {
                    convertView.findViewById(R.id.divider_view).setVisibility(View.VISIBLE);
                }

                TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
                tv.setText(getTitle(position));

                return convertView;
            }

            @Override
            public void registerDataSetObserver(DataSetObserver observer) {

            }

            @Override
            public void unregisterDataSetObserver(DataSetObserver observer) {

            }

            @Override
            public int getCount() {
                return titles.length;
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public boolean hasStableIds() {
                return false;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null || !convertView.getTag().toString().equals(TAG_DROPDOWN)) {
                    convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.spinner_actionbar,
                            parent, false);
                    convertView.setTag(TAG_DROPDOWN);
                }

                TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
                tv.setText(getTitle(position));

                return convertView;
            }

            @Override
            public int getItemViewType(int position) {
                return 0;
            }

            @Override
            public int getViewTypeCount() {
                return 1;
            }

            @Override
            public boolean isEmpty() {
                return false;
            }

            private String getTitle(int position) {
                return titles[position];
            }
        });

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            int[] colors = getResources().getIntArray(R.array.spinner_videos_color_array);
            int actualPosition = 0;

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Filter filter = ((CursorRecyclerAdapter) listView.getAdapter()).getFilter();

                UiUtils.animateToolbarStatusBarColor(mToolbar, mStatusBarBg, colors[position],
                        colors[actualPosition]);

                switch (position) {
                case 0:
                    filter.filter(null);
                    break;

                case 1:
                    filter.filter("playlist_wtc");
                    break;

                case 2:
                    filter.filter("playlist_lvn");
                    break;
                }

                actualPosition = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private ValueAnimator.AnimatorUpdateListener mColorAnimListener = new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            mToolbar.setBackgroundColor((Integer) animation.getAnimatedValue());
        }
    };

    //**********************************************************************************************
    //* LoaderManager                                                                              *
    //**********************************************************************************************
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String[] projection = { ProviderContract.SoundEntry._ID, ProviderContract.VideosEntry.COLUMN_NAME_VIDEO_ID,
                ProviderContract.VideosEntry.COLUMN_NAME_DESC, ProviderContract.VideosEntry.COLUMN_NAME_PAGE,
                ProviderContract.VideosEntry.COLUMN_NAME_TIMESTAMP };
        Uri uri = ProviderConstants.VIDEOS_URI;

        String where = null;
        if (args != null) {
            where = ProviderContract.VideosEntry.COLUMN_NAME_PAGE + "=\""
                    + args.getCharSequence(ARG_LOADER_WHERE).toString() + '"';
        }
        return new CursorLoader(mContext, uri, projection, where, null,
                ProviderContract.VideosEntry.COLUMN_NAME_TIMESTAMP + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        if (cursor.isClosed()) {
            Activity activity = getActivity();
            if (activity != null) {
                getLoaderManager().restartLoader(MainActivity.VIDEOS, null, this);
            }
            return;
        }
        Cursor oldCursor = ((CursorRecyclerAdapter) listView.getAdapter()).swapCursor(cursor);
        if (oldCursor != null && !oldCursor.isClosed())
            oldCursor.close();
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        Cursor oldCursor = ((CursorRecyclerAdapter) listView.getAdapter()).swapCursor(null);
        if (oldCursor != null && !oldCursor.isClosed())
            oldCursor.close();
        ;
    }
}