ca.zadrox.dota2esportticker.ui.MatchActivity.java Source code

Java tutorial

Introduction

Here is the source code for ca.zadrox.dota2esportticker.ui.MatchActivity.java

Source

/*
 * Copyright 2014 Nicholas Liu
 *
 * 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 ca.zadrox.dota2esportticker.ui;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.HashSet;
import java.util.Set;

import ca.zadrox.dota2esportticker.BuildConfig;
import ca.zadrox.dota2esportticker.R;
import ca.zadrox.dota2esportticker.service.ReminderAlarmService;
import ca.zadrox.dota2esportticker.service.UpdateMatchService;
import ca.zadrox.dota2esportticker.ui.widget.MultiSwipeRefreshLayout;
import ca.zadrox.dota2esportticker.ui.widget.SlidingTabLayout;
import ca.zadrox.dota2esportticker.util.UIUtils;
import ca.zadrox.dota2esportticker.util.steamapi.SteamAuth;

/**
 * Created by Acco on 10/27/2014.
 */
public class MatchActivity extends BaseActivity
        implements MatchListFragment.FragmentListener, MultiSwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = MatchActivity.class.getSimpleName();
    private static final String ARG_MATCH_TICKER_TYPE = "ca.zadrox.dota2esportticker.ARG_MATCH_TICKER_TYPE";
    ViewPager mViewPager = null;
    MatchPagerAdapter mMatchPagerAdapter = null;
    SlidingTabLayout mSlidingTabLayout = null;
    MultiSwipeRefreshLayout mSwipeRefreshLayout = null;
    ListView mCurrentListView;

    private boolean mWideMode = false;
    private Set<MatchListFragment> mMatchListFragments = new HashSet<MatchListFragment>();

    public MatchActivity() {
    }

    @Override
    protected int getSelfNavDrawerItem() {
        return NAVDRAWER_ITEM_MATCHES;
    }

    @Override
    protected void onResume() {
        super.onResume();
        int i = mViewPager.getCurrentItem();
        for (MatchListFragment fragment : mMatchListFragments) {

            if (fragment.getArguments().getInt(MatchListFragment.ARG_LIST_POSITION) == i) {
                if (mCurrentListView != null) {
                    mCurrentListView.setOnScrollListener(new AbsListView.OnScrollListener() {
                        @Override
                        public void onScrollStateChanged(AbsListView view, int scrollState) {

                        }

                        @Override
                        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                                int totalItemCount) {

                        }
                    });
                }
                enableActionBarAutoHide(fragment.getListView());
                mCurrentListView = fragment.getListView();
            }
        }

        LocalBroadcastManager.getInstance(this).registerReceiver(mUpdateCompleteReceiver,
                new IntentFilter(UpdateMatchService.UPDATE_COMPLETE));

        LocalBroadcastManager.getInstance(this).registerReceiver(mUpdateStartedReceiver,
                new IntentFilter(UpdateMatchService.UPDATE_STARTED));

        LocalBroadcastManager.getInstance(this).registerReceiver(mNoConnectionReceiver,
                new IntentFilter(UpdateMatchService.UPDATE_NO_CONNECTIVITY));

        LocalBroadcastManager.getInstance(this).registerReceiver(mSteamAPIKeyIncorrectReceiver,
                new IntentFilter(SteamAuth.STEAM_API_KEY_INCORRECT));

        this.startService(
                new Intent(UpdateMatchService.ACTION_UPDATE_RESULTS, null, this, UpdateMatchService.class));

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_matches);

        mViewPager = (ViewPager) findViewById(R.id.view_pager);

        mSwipeRefreshLayout = (MultiSwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setCanChildScrollUpCallback(this);

        mMatchPagerAdapter = new MatchPagerAdapter(getFragmentManager());
        mViewPager.setAdapter(mMatchPagerAdapter);

        mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);

        Resources res = getResources();
        mSlidingTabLayout.setSelectedIndicatorColors(res.getColor(R.color.tab_selected_strip));
        mSlidingTabLayout.setDistributeEvenly(true);
        mSlidingTabLayout.setViewPager(mViewPager);

        if (mSlidingTabLayout != null) {
            mSlidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int i, float v, int i2) {

                }

                @Override
                public void onPageSelected(int i) {
                    for (MatchListFragment fragment : mMatchListFragments) {

                        if (fragment.getArguments().getInt(MatchListFragment.ARG_LIST_POSITION) == i) {
                            if (mCurrentListView != null) {
                                // why set an empty onscroll listener?
                                // enableactionbarautohide sets its own one, and we need to remove it.
                                mCurrentListView.setOnScrollListener(new AbsListView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(AbsListView view, int scrollState) {

                                    }

                                    @Override
                                    public void onScroll(AbsListView view, int firstVisibleItem,
                                            int visibleItemCount, int totalItemCount) {

                                    }
                                });
                            }
                            enableActionBarAutoHide(fragment.getListView());
                            mCurrentListView = fragment.getListView();
                        }

                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                    enableDisableSwipeRefresh(state == ViewPager.SCROLL_STATE_IDLE);
                }
            });
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intentx;
        switch (item.getItemId()) {
        case R.id.menu_refresh:
            setRefreshingState(true);
            onRefresh();
            break;
        case R.id.menu_debug_notify:
            intentx = new Intent(ReminderAlarmService.ACTION_NOTIFY_DEBUG);
            intentx.setClass(this, ReminderAlarmService.class);
            this.startService(intentx);
            return true;
        case R.id.menu_debug_view_live_match:
            final Intent intent = new Intent(this, LiveGameStatsActivity.class);
            intent.putExtra(LiveGameStatsActivity.ARGS_GAME_TLL, (String) null);
            intent.putExtra(LiveGameStatsActivity.ARGS_GAME_TLR, (String) null);
            intent.putExtra(LiveGameStatsActivity.ARGS_GAME_BO, "best of 1");
            intent.putExtra(LiveGameStatsActivity.ARGS_GAME_TNL, "Invasion");
            intent.putExtra(LiveGameStatsActivity.ARGS_GAME_TNR, "Koopa");
            intent.putExtra(LiveGameStatsActivity.ARGS_GAME_TN, "awesome");

            final Context mContext = this;

            AlertDialog.Builder alert = new AlertDialog.Builder(this);

            alert.setTitle("Enter Match Id:");

            // Set an EditText view to get user input
            final EditText input = new EditText(this);
            alert.setView(input);

            alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    intent.putExtra(LiveGameStatsActivity.ARGS_GAME_MID,
                            Long.parseLong(input.getText().toString()));
                    mContext.startActivity(intent);
                }
            });

            alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
            });

            alert.show();

            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * This method overrides the default behaviour of the swipe refresh layout, letting the
     * list in the listfragment scroll first
     */
    @Override
    public boolean canSwipeRefreshChildScrollUp() {

        for (MatchListFragment fragment : mMatchListFragments) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                if (!fragment.getUserVisibleHint()) {
                    continue;
                }
            }
            return ViewCompat.canScrollVertically(fragment.getListView(), -1);
        }

        return false;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        registerHideableHeaderView(findViewById(R.id.header_bar));
        getContentTopClearance();
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mUpdateCompleteReceiver);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mUpdateStartedReceiver);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mNoConnectionReceiver);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mSteamAPIKeyIncorrectReceiver);

        super.onPause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.matches, menu);

        MenuItem notificationItem = menu.findItem(R.id.menu_debug_notify);
        if (notificationItem != null) {
            notificationItem.setVisible(BuildConfig.DEBUG);
        }

        MenuItem matchMenuItem = menu.findItem(R.id.menu_debug_view_live_match);
        if (matchMenuItem != null) {
            matchMenuItem.setVisible(BuildConfig.DEBUG);
        }

        return true;
    }

    @Override
    public void onFragmentViewCreated(ListFragment fragment) {
        if (fragment.getUserVisibleHint()) {
            mCurrentListView = fragment.getListView();
            enableActionBarAutoHide(mCurrentListView);
        }
    }

    @Override
    public void onFragmentAttached(MatchListFragment fragment) {
        mMatchListFragments.add(fragment);
    }

    @Override
    public void onFragmentDetached(MatchListFragment fragment) {
        mMatchListFragments.remove(fragment);
    }

    @Override
    public void onRefresh() {
        this.startService(
                new Intent(UpdateMatchService.ACTION_UPDATE_MATCHES, null, this, UpdateMatchService.class));
    }

    public void setRefreshingState(boolean isRefreshing) {
        onRefreshingStateChanged(isRefreshing);
    }

    private int getContentTopClearance() {

        View slidingTabs = findViewById(R.id.sliding_tabs);

        final boolean slidingTabsVisible = slidingTabs != null && slidingTabs.getVisibility() == View.VISIBLE;

        int actionBarClearance = UIUtils.calculateActionBarSize(this);
        int slidingTabsClearance = slidingTabsVisible
                ? getResources().getDimensionPixelSize(R.dimen.tab_indicator_height)
                : 0;
        int gridPadding = getResources().getDimensionPixelSize(R.dimen.explore_grid_padding);

        int contentTopPadding = actionBarClearance + slidingTabsClearance + gridPadding;

        setProgressBarTopWhenActionBarShown(actionBarClearance + slidingTabsClearance);
        //mDrawShadowFrameLayout.setShadowTopOffset(actionBarClearance + secondaryClearance);

        return contentTopPadding;
    }

    private BroadcastReceiver mUpdateCompleteReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            setRefreshingState(false);
        }
    };

    private BroadcastReceiver mUpdateStartedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            setRefreshingState(true);
        }
    };

    private BroadcastReceiver mNoConnectionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "No Connection", Toast.LENGTH_SHORT).show();
            setRefreshingState(false);
        }
    };

    private BroadcastReceiver mSteamAPIKeyIncorrectReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Steam Web API Key incorrect. Double check settings.", Toast.LENGTH_SHORT)
                    .show();
        }
    };

    private class MatchPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int i) {
            MatchListFragment fragment = new MatchListFragment();
            Bundle args = new Bundle();
            args.putInt(MatchListFragment.ARG_LIST_POSITION, i);
            args.putInt(MatchListFragment.ARG_LIST_PADDING, getContentTopClearance());
            fragment.setArguments(args);
            return fragment;
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
            case 0:
                return getString(R.string.tab_title_upcoming);
            case 1:
                return getString(R.string.tab_title_live);
            case 2:
                return getString(R.string.tab_title_concluded);
            }
            return super.getPageTitle(position);
        }
    }
}