public class DataBindingActivity extends AppCompatActivity {

    private Context mContext;

    private ActivityDataBinding binding;
    private Toolbar toolbar;

    private DrawerLayout drawerLayout;

    private InfoAdapter adapter;
    private LinearLayoutManager mgr;
    private int visibleThreshold = 2;
    private boolean loading = false;

    private boolean isFirst = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_data);

        if (findViewById(R.id.toolbar) != null){
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        initView();
    }

    public void initView() {
        mContext = this;

        drawerLayout = binding.drawer;
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END);
        drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View view, float v) {}

            @Override
            public void onDrawerOpened(View view) {
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.END);
            }

            @Override
            public void onDrawerStateChanged(int i) {}

            @Override
            public void onDrawerClosed(View view) {
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END);
            }
        });

        RecyclerView recyclerView = binding.recyclerView;
        mgr = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mgr);
        adapter = new InfoAdapter(new InfoAdapter.OnItemClick() {
            @Override
            public void click(int index) {
                if (index % 3 == 0) {
                    showDialog();
                } else if (index % 3 == 1) {
                    Dialog dialog = ViewUtils.createLoadingDialog(mContext);
                    dialog.show();
                } else {
                    CustomDialogFragment dialog = CustomDialogFragment.newInstance("Demo");
                    dialog.show(getFragmentManager(), "");
                }
            }
        });
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int totalItemCount = mgr.getItemCount();
                int lastVisibleItem = mgr.findLastVisibleItemPosition();
                if (!loading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                    loading = true;
                    loadMore();
                }
            }
        });
    }

    public void loadMore() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isFirst) {
                            adapter.addData();
                            isFirst = false;
                            loading = false;
                        } else {
                            adapter.hideProgress();
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }, 3000);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.drawer, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home){
            onBackPressed();
        } else if (id == R.id.action_filter) {
            if(drawerLayout.isDrawerOpen(GravityCompat.END)){
                drawerLayout.closeDrawers();
            } else{
                drawerLayout.openDrawer(GravityCompat.END);
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void showDialog() {
        final BottomSheetDialog dialog = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_sheet, null);
        TextView tvName = (TextView) view.findViewById(R.id.tv_name);
        RecyclerView rvList = (RecyclerView) view.findViewById(R.id.rv_list);

        tvName.setText("SELECT LESSON");
        rvList.setLayoutManager(new LinearLayoutManager(this));
        InfoAdapter adapter = new InfoAdapter(false, new InfoAdapter.OnItemClick() {
            @Override
            public void click(int index) {
                dialog.dismiss();
                Toast.makeText(mContext, "Lesson " + index, Toast.LENGTH_SHORT).show();
            }
        });
        rvList.setAdapter(adapter);

        dialog.setContentView(view);
        dialog.show();
    }
} public class LoginActivity extends BaseActivity {

    private Context mContext;

    @ViewId(R.id.tl_name)
    private TextInputLayout tlName;
    @ViewId(R.id.tt_name)
    private TextInputEditText ttName;

    @ViewId(R.id.tl_pwd)
    private TextInputLayout tlPwd;
    @ViewId(R.id.tt_pwd)
    private TextInputEditText ttPwd;

    @ViewId(R.id.btn_login)
    Button btnLogin;

    @Override
    protected void setListeners() {
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = tlName.getEditText().getText().toString();
                String password = tlPwd.getEditText().getText().toString();

                if (username.equals(password)) {
                    IntentManager.startDataBindingActivity(mContext);
                } else {
                    tlPwd.setErrorEnabled(true);
                    tlPwd.setError("wrong password");
                }
            }
        });

        ttPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tlPwd.setErrorEnabled(false);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        mContext = this;
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_login;
    }
} public class MPanelViewActivity extends BaseActivity {

    @ViewId(R.id.pv_test)
    private MPanelView mPanelView;

    @Override
    protected void setListeners() {

    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {

    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_mpanelview;
    }
} public class AnimationActivity extends BaseActivity {

    @ViewId(R.id.btn_animation)
    private Button button;
    @ViewId(R.id.btn_point_animation)
    private Button buttonPoint;
    @ViewId(R.id.text_animation)
    private TextView textview;

    private Context mContext;

    @Override
    protected void setListeners() {
        button.setOnClickListener(this);
        buttonPoint.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_animation:
                startAnimation();
                break;
            case R.id.btn_point_animation:
                Intent intent = new Intent();
                intent.setClass(mContext, AnimatorViewActivity.class);
                mContext.startActivity(intent);
                break;
        }
    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        mContext = this;
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_animation;
    }

    public void startAnimation() {
//        ObjectAnimator animator = ObjectAnimator.ofFloat(textview, "rotation", 0f, 360f);
//        animator.setDuration(5000);
//        animator.start();

//        ObjectAnimator moveIn = ObjectAnimator.ofFloat(textview, "translationX", 0f - textview.getWidth(), 0f);
//        ObjectAnimator rotate = ObjectAnimator.ofFloat(textview, "rotation", 0f, 360f);
//        ObjectAnimator fadeInOut = ObjectAnimator.ofFloat(textview, "alpha", 1f, 0f, 1f);
//        AnimatorSet animSet = new AnimatorSet();
//        animSet.play(rotate).with(fadeInOut).after(moveIn);
//        animSet.setDuration(5000);
//        animSet.start();

        Animator animator = AnimatorInflater.loadAnimator(mContext, R.animator.animator_text);
        animator.setTarget(textview);
        animator.start();

        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                Toast.makeText(mContext, "start", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                Toast.makeText(mContext, "finish", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
    }
} public class AppBarDetailActivity extends AppCompatActivity {

    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appbar_detail);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });


        CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle("考研英语核心500词");

//        ImageView ivImage = (ImageView)findViewById(R.id.ivImage);
//        ivImage.setImageResource(R.drawable.book1);

        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(mViewPager);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.addTab(tabLayout.newTab().setText("内容简介"));
        tabLayout.addTab(tabLayout.newTab().setText("作者简介"));
        tabLayout.addTab(tabLayout.newTab().setText("目录"));
        tabLayout.setupWithViewPager(mViewPager);
    }

    private void setupViewPager(ViewPager mViewPager) {
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(DetailFragment.newInstance(getAsset("book_content.txt")), "内容简介");
        adapter.addFragment(DetailFragment.newInstance(getAsset("book_author.txt")), "作者简介");
        adapter.addFragment(DetailFragment.newInstance(getAsset("book_menu.txt")), "目录");
        mViewPager.setAdapter(adapter);
    }

    private String getAsset(String fileName) {
        AssetManager am = getResources().getAssets();
        InputStream is = null;
        try {
            is = am.open(fileName, AssetManager.ACCESS_BUFFER);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Scanner(is).useDelimiter("\\Z").next();
    }


    static class MyPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

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

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
} public class AudioPlayerActivity extends BaseActivity {

    @ViewId(R.id.audio_player)
    private AudioPlayerView audioPlayerView;

    @Override
    protected void setListeners() {

    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        String path = Environment.getExternalStorageDirectory() + "/Music/Download/mp3/test.mp3";
        audioPlayerView.setContent(path);
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_audio_player;
    }
} public class CalendarMonthActivity extends BaseFragmentActivity {

    @ViewId(R.id.vp_calendar_month)
    private ViewPager viewPager;
    @ViewId(R.id.tv_month)
    private TextView tvMonth;

    private String month;

    private Context mContext;

    @Override
    protected void setListeners() {
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                Calendar calendar = Utils.getSelectCalendar(position);
                month = calendar.get(Calendar.YEAR)
                        + "-"
                        + Utils.LeftPad_Tow_Zero(calendar.get(Calendar.MONTH) + 1);
                tvMonth.setText(month);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_calendar_month;
    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls(Bundle savedInstanceState) {
        mContext = this;
        ScreenSlidePagerAdapter screenSlidePagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
        viewPager.setAdapter(screenSlidePagerAdapter);
        viewPager.setCurrentItem(500);
        tvMonth = (TextView) this.findViewById(R.id.tv_month);
        month = Calendar.getInstance().get(Calendar.YEAR)
                + "-"
                + Utils.LeftPad_Tow_Zero(Calendar.getInstance().get(Calendar.MONTH) + 1);
        tvMonth.setText(month);
    }

    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return CalendarFragment.create(position, new CalendarFragment.OnDayClickListener() {
                @Override
                public void onClick() {
                    IntentManager.startMPanelViewActivity(mContext);
                }
            });
        }

        @Override
        public int getCount() {
            return 1000;
        }
    }
} public class IJKPlayerActivity extends AppCompatActivity {
    GiraffePlayer player;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ijkplayer);
        player = new GiraffePlayer(this);


//        player.onComplete(new Runnable() {
//            @Override
//            public void run() {
//                //callback when video is finish
//                Toast.makeText(getApplicationContext(), "video play completed", Toast.LENGTH_SHORT).show();
//            }
//        }).onInfo(new GiraffePlayer.OnInfoListener() {
//            @Override
//            public void onInfo(int what, int extra) {
//                switch (what) {
//                    case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
//                        //do something when buffering start
//                        break;
//                    case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
//                        //do something when buffering end
//                        break;
//                    case IMediaPlayer.MEDIA_INFO_NETWORK_BANDWIDTH:
//                        //download speed
//                        ((TextView) findViewById(R.id.tv_speed)).setText(Formatter.formatFileSize(getApplicationContext(), extra) + "/s");
//                        break;
//                    case IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
//                        //do something when video rendering
//                        findViewById(R.id.tv_speed).setVisibility(View.GONE);
//                        break;
//                }
//            }
//        }).onError(new GiraffePlayer.OnErrorListener() {
//            @Override
//            public void onError(int what, int extra) {
//                Toast.makeText(getApplicationContext(), "video play error", Toast.LENGTH_SHORT).show();
//            }
//        });



        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.btn_play) {
                    String url = ((EditText) findViewById(R.id.et_url)).getText().toString();
                    player.play(url);
                    player.setTitle(url);
                } else if (v.getId() == R.id.btn_play_sample_1) {
                    String url = "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8";
                    ((EditText) findViewById(R.id.et_url)).setText(url);
                    player.play(url);
                    player.setTitle(url);
                } else if (v.getId() == R.id.btn_play_sample_2) {
                    String url = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
//                    url = "http://stream.youdao.com/cetVideo/CET6/1_201506_01/1writing.mp4";
                    ((EditText) findViewById(R.id.et_url)).setText(url);
                    player.play(url);
                    player.setTitle(url);
//                    player.setShowNavIcon(false);
                } else if (v.getId() == R.id.btn_play_sample_3) {
                    String url = "https://r13---sn-o097znes.googlevideo.com/videoplayback?mt=1455852432&mv=m&ms=au&source=youtube&key=yt6&requiressl=yes&mm=31&mn=sn-o097znes&initcwndbps=16485000&id=o-AEGdeTbgSTzVGqwV2s8MjH5mlDPz3APWVwGfftr9GDqy&upn=D3A5w5WYU1k&lmt=1410665930307178&ip=2600:3c01::f03c:91ff:fe70:35ff&sparams=dur,id,initcwndbps,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,requiressl,source,upn,expire&fexp=9416126,9420452,9422596,9423341,9423661,9423662,9424038,9424862,9425077,9425730,9426472,9426698,9427379,9428544,9428649,9429218,9429237,9429435,9429589&pl=32&dur=106.370&sver=3&expire=1455874197&nh=IgpwcjAxLnNqYzA3KgkxMjcuMC4wLjE&ratebypass=yes&mime=video/mp4&itag=18&signature=22C4633FCD1259D5F6CD1E0B54AB649982895534.378BAAC5AFAAEA737246C5CE5B92212E40B765BD&ipbits=0";
                    ((EditText) findViewById(R.id.et_url)).setText(url);
                    player.play(url);
                    player.setTitle(url);
//                    player.setShowNavIcon(false);
                } else if (v.getId() == R.id.btn_open) {
                    String url = ((EditText) findViewById(R.id.et_url)).getText().toString();
                    GiraffePlayerActivity.configPlayer(IJKPlayerActivity.this).setTitle(url).play(url);
//                    more configuration example:
//                    GiraffePlayerActivity.configPlayer(MainActivity.this)
//                            .setScaleType(GiraffePlayer.SCALETYPE_FITPARENT)
//                            .setDefaultRetryTime(5 * 1000)
//                            .setFullScreenOnly(false)
//                            .setTitle(url)
//                            .play(url);
                } else if (v.getId() == R.id.btn_start) {
                    player.start();
                } else if (v.getId() == R.id.btn_pause) {
                    player.pause();
                } else if (v.getId() == R.id.btn_toggle) {
                    player.toggleFullScreen();
                } else if (v.getId() == R.id.btn_forward) {
                    player.forward(0.2f);
                } else if (v.getId() == R.id.btn_back) {
                    player.forward(-0.2f);
                } else if (v.getId() == R.id.btn_toggle_ratio) {
                    player.toggleAspectRatio();
                }
            }
        };
        findViewById(R.id.btn_play).setOnClickListener(clickListener);
        findViewById(R.id.btn_play_sample_1).setOnClickListener(clickListener);
        findViewById(R.id.btn_play_sample_2).setOnClickListener(clickListener);
        findViewById(R.id.btn_play_sample_3).setOnClickListener(clickListener);
        findViewById(R.id.btn_pause).setOnClickListener(clickListener);
        findViewById(R.id.btn_start).setOnClickListener(clickListener);
        findViewById(R.id.btn_toggle).setOnClickListener(clickListener);
        findViewById(R.id.btn_open).setOnClickListener(clickListener);
        findViewById(R.id.btn_forward).setOnClickListener(clickListener);
        findViewById(R.id.btn_back).setOnClickListener(clickListener);
        findViewById(R.id.btn_toggle_ratio).setOnClickListener(clickListener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
            player.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player != null) {
            player.onResume();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.onDestroy();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (player != null) {
            player.onConfigurationChanged(newConfig);
        }
    }

    @Override
    public void onBackPressed() {
        if (player != null && player.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }
} public class ListActivity extends BaseActivity {

//    @ViewId(R.id.id_listview)
//    private ListView mRecyclerView;

    @ViewId(R.id.expand_list)
    private ExpandableListView expandableListView;

    private List<Map<String, Object>> mDatas = new ArrayList<>();
    private ArrayList<CourseItem> mCourses = new ArrayList<>();

    private Myadapter mAdapter;
    private MExpandAdapter mExpandAdapter;

    private Context mContext;
    final public static int  SIGN_UP = 1;

    private Handler mUIhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case SIGN_UP:
//                    ConfirmDialog confirmDialog = new ConfirmDialog(ListActivity.this, R.style.MyDialog);
//                    confirmDialog.setMsg(getString(R.string.start_list_activity));
//                    confirmDialog.setPositiveButton(mContext.getResources().getString(R.string.confirm), new ConfirmDialog.CustomOnClick() {
//                        @Override
//                        public void onClick() {
//                        }
//                    });
//                    confirmDialog.setNegativeButton(mContext.getResources().getString(R.string.cancel), null);
//                    confirmDialog.show();

                    final MaterialDialog mMaterialDialog = new MaterialDialog(mContext);
                    mMaterialDialog.setTitle("MaterialDialog");
                    mMaterialDialog.setMessage("Hello world!");
                    mMaterialDialog.setPositiveButton("OK", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mMaterialDialog.dismiss();
                        }
                    });
                    mMaterialDialog.setNegativeButton("CANCEL", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mMaterialDialog.dismiss();
                        }
                    });

                    mMaterialDialog.show();

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setListeners() {

    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        mContext = this;
        initData();
//        mAdapter = new Myadapter(this);
//        mRecyclerView.setAdapter(mAdapter);

        mExpandAdapter = new MExpandAdapter(this);
        mExpandAdapter.setData(mCourses);
        expandableListView.setAdapter(mExpandAdapter);
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                mUIhandler.sendEmptyMessage(ListActivity.SIGN_UP);
                return false;
            }
        });
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_list;
    }

    protected void initData() {
        Map<String, Object> map = new HashMap<>();
        map.put("title", "G1");
        map.put("info", "item1");
        TextDrawable drawable = TextDrawable.builder()
                .buildRect("M", Color.RED);
        map.put("img", drawable);
        mDatas.add(map);
        mDatas.add(map);
        mDatas.add(map);

        CourseItem courseItem = new CourseItem();
        courseItem.setCourseName("Test");
        ArrayList<Lesson> lessons = new ArrayList<>();
        lessons.add(new Lesson("lesson1", "Mary"));
        lessons.add(new Lesson("lesson2", "Jack"));
        lessons.add(new Lesson("lesson3", "Tom"));
        lessons.add(new Lesson("lesson4", "Jack"));
        courseItem.setLessons(lessons);
        mCourses.add(courseItem);
        mCourses.add(courseItem);
    }

    class Myadapter extends BaseAdapter {

        private LayoutInflater mInflater;

        public Myadapter (Context context) {
            this.mInflater = LayoutInflater.from(context);
        }

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

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.view_custom_item, null);
                holder.img = (ImageView) convertView.findViewById(R.id.imageView);
                holder.title = (TextView) convertView.findViewById(R.id.title);
                holder.info = (TextView) convertView.findViewById(R.id.info);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.img.setImageDrawable((TextDrawable) mDatas.get(position).get("img"));
            holder.title.setText((String) mDatas.get(position).get("title"));
            holder.info.setText((String) mDatas.get(position).get("info"));

            return convertView;
        }
    }

    class ViewHolder {
        public ImageView img;
        public TextView title;
        public TextView info;
    }
} public class NotificationActivity extends BaseActivity {

    @ViewId(R.id.btn_simple_notification)
    private Button btnSimpleNotification;
    @ViewId(R.id.btn_back_notification)
    private Button btnBackNotification;
    @ViewId(R.id.btn_clear_notification)
    private Button btnClearNotification;
    @ViewId(R.id.btn_progress_notification)
    private Button btnProgressNotification;
    @ViewId(R.id.btn_start_download)
    private Button btnStartDownload;

    private NotificationCompat.Builder mBuilder;
    private NotificationManager mNotificationManager;

    private int progress = 0;
    private boolean indeterminate = false;

    private Context mContext;


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_simple_notification:
                showSimpleNotification();
                break;
            case R.id.btn_back_notification:
                showNotification();
                break;
            case R.id.btn_progress_notification:
                showProgressNotification();
                break;
            case R.id.btn_clear_notification:
                clearNotification();
                break;
            case R.id.btn_start_download:
                startDownload();
                break;
            default:
                break;
        }
    }

    @Override
    protected void setListeners() {
        btnSimpleNotification.setOnClickListener(this);
        btnBackNotification.setOnClickListener(this);
        btnClearNotification.setOnClickListener(this);
        btnProgressNotification.setOnClickListener(this);
        btnStartDownload.setOnClickListener(this);
    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        mContext = this;
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_notification;
    }

    public void showSimpleNotification() {
        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("Hello World")
                .setContentText("This is a simple notification.")
                .setSmallIcon(R.drawable.ic_launcher);
        Intent resultIntent = new Intent(this, NotificationActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        Notification notification = mBuilder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(0, notification);
    }

    public void showNotification() {
        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("Hello World")
                .setContentText("This is a simple notification.")
                .setSmallIcon(R.drawable.ic_launcher);
        Intent resultIntent = new Intent(this, NotificationActivity.class);
        resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(NotificationActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent pendingIntent =
                stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

//        Intent backIntent = new Intent(this, MainActivity.class);
//        Intent intent = new Intent(this, NotificationActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//        PendingIntent pendingIntent = PendingIntent.getActivities(this, 0,
//                new Intent[] {backIntent, intent}, PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder.setContentIntent(pendingIntent);
        Notification notification = mBuilder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(0, notification);
    }

    public void showProgressNotification() {
        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("Download")
                .setContentText("Progress rate:")
                .setSmallIcon(R.drawable.ic_launcher);
        if(indeterminate){
            mBuilder.setProgress(0, 0, true);
        } else{
            mBuilder.setProgress(100, progress, false);
        }
        mNotificationManager.notify(1, mBuilder.build());
    }

    public void clearNotification() {
        mNotificationManager.cancelAll();
    }

    public void startDownload() {
        showProgressNotification();
        MDownloadTask asyncTask = new MDownloadTask(mNotificationManager, mBuilder, mContext);
        asyncTask.execute();
    }
} public class PinnedSectionListActivity extends ListActivity implements OnClickListener {

    static class SimpleAdapter extends ArrayAdapter<Item> implements PinnedSectionListView.PinnedSectionListAdapter {

        private static final int[] COLORS = new int[] {
            R.color.green_light, R.color.orange_light,
            R.color.blue_light, R.color.red_light };

        public SimpleAdapter(Context context, int resource, int textViewResourceId) {
            super(context, resource, textViewResourceId);
            generateDataset('A', 'Z', false);
        }

        public void generateDataset(char from, char to, boolean clear) {
        	
        	if (clear) clear();
        	
            final int sectionsNumber = to - from + 1;
            prepareSections(sectionsNumber);

            int sectionPosition = 0, listPosition = 0;
            for (char i=0; i<sectionsNumber; i++) {
                Item section = new Item(Item.SECTION, String.valueOf((char)('A' + i)));
                section.sectionPosition = sectionPosition;
                section.listPosition = listPosition++;
                onSectionAdded(section, sectionPosition);
                add(section);

                final int itemsNumber = (int) Math.abs((Math.cos(2f*Math.PI/3f * sectionsNumber / (i+1f)) * 25f));
                for (int j=0;j<itemsNumber;j++) {
                    Item item = new Item(Item.ITEM, section.text.toUpperCase(Locale.ENGLISH) + " - " + j);
                    item.sectionPosition = sectionPosition;
                    item.listPosition = listPosition++;
                    add(item);
                }

                sectionPosition++;
            }
        }
        
        protected void prepareSections(int sectionsNumber) { }
        protected void onSectionAdded(Item section, int sectionPosition) { }

        @Override public View getView(int position, View convertView, ViewGroup parent) {
            TextView view = (TextView) super.getView(position, convertView, parent);
            view.setTextColor(Color.DKGRAY);
            view.setTag("" + position);
            Item item = getItem(position);
            if (item.type == Item.SECTION) {
                //view.setOnClickListener(PinnedSectionListActivity.this);
                view.setBackgroundColor(parent.getResources().getColor(COLORS[item.sectionPosition % COLORS.length]));
            }
            return view;
        }

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

        @Override public int getItemViewType(int position) {
            return getItem(position).type;
        }

        @Override
        public boolean isItemViewTypePinned(int viewType) {
            return viewType == Item.SECTION;
        }

    }

    static class FastScrollAdapter extends SimpleAdapter implements SectionIndexer {

        private Item[] sections;

        public FastScrollAdapter(Context context, int resource, int textViewResourceId) {
            super(context, resource, textViewResourceId);
        }

        @Override protected void prepareSections(int sectionsNumber) {
            sections = new Item[sectionsNumber];
        }

        @Override protected void onSectionAdded(Item section, int sectionPosition) {
            sections[sectionPosition] = section;
        }

        @Override public Item[] getSections() {
            return sections;
        }

        @Override public int getPositionForSection(int section) {
            if (section >= sections.length) {
                section = sections.length - 1;
            }
            return sections[section].listPosition;
        }

        @Override public int getSectionForPosition(int position) {
            if (position >= getCount()) {
                position = getCount() - 1;
            }
            return getItem(position).sectionPosition;
        }

    }

	static class Item {

		public static final int ITEM = 0;
		public static final int SECTION = 1;

		public final int type;
		public final String text;

		public int sectionPosition;
		public int listPosition;

		public Item(int type, String text) {
		    this.type = type;
		    this.text = text;
		}

		@Override public String toString() {
			return text;
		}

	}

	private boolean hasHeaderAndFooter;
	private boolean isFastScroll = true;
	private boolean addPadding;
	private boolean isShadowVisible = true;
	private int mDatasetUpdateCount;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pinned);
		if (savedInstanceState != null) {
		    isFastScroll = savedInstanceState.getBoolean("isFastScroll");
		    addPadding = savedInstanceState.getBoolean("addPadding");
		    isShadowVisible = savedInstanceState.getBoolean("isShadowVisible");
		    hasHeaderAndFooter = savedInstanceState.getBoolean("hasHeaderAndFooter");
		}
		initializeHeaderAndFooter();
		initializeAdapter();
		initializePadding();
	}

    @Override
	protected void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    outState.putBoolean("isFastScroll", isFastScroll);
	    outState.putBoolean("addPadding", addPadding);
	    outState.putBoolean("isShadowVisible", isShadowVisible);
	    outState.putBoolean("hasHeaderAndFooter", hasHeaderAndFooter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
	    Item item = (Item) getListView().getAdapter().getItem(position);
	    if (item != null) {
	        Toast.makeText(this, "Item " + position + ": " + item.text, Toast.LENGTH_SHORT).show();
	    } else {
	        Toast.makeText(this, "Item " + position, Toast.LENGTH_SHORT).show();
	    }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		menu.getItem(0).setChecked(isFastScroll);
		menu.getItem(1).setChecked(addPadding);
		menu.getItem(2).setChecked(isShadowVisible);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
    	    case R.id.action_fastscroll:
    	        isFastScroll = !isFastScroll;
    	        item.setChecked(isFastScroll);
    	        initializeAdapter();
    	        break;
    	    case R.id.action_addpadding:
    	        addPadding = !addPadding;
    	        item.setChecked(addPadding);
    	        initializePadding();
    	        break;
    	    case R.id.action_showShadow:
    	        isShadowVisible = !isShadowVisible;
    	        item.setChecked(isShadowVisible);
    	        ((PinnedSectionListView)getListView()).setShadowVisible(isShadowVisible);
    	        break;
    	    case R.id.action_showHeaderAndFooter:
    	        hasHeaderAndFooter = !hasHeaderAndFooter;
    	        item.setChecked(hasHeaderAndFooter);
    	        initializeHeaderAndFooter();
    	        break;
    	    case R.id.action_updateDataset:
    	    	updateDataset();
    	    	break;
	    }
	    return true;
	}

	private void updateDataset() {
		mDatasetUpdateCount++;
		SimpleAdapter adapter = (SimpleAdapter) getListAdapter();
		switch (mDatasetUpdateCount % 4) {
			case 0: adapter.generateDataset('A', 'B', true); break;
			case 1: adapter.generateDataset('C', 'M', true); break;
			case 2: adapter.generateDataset('P', 'Z', true); break;
			case 3: adapter.generateDataset('A', 'Z', true); break;
		}
		adapter.notifyDataSetChanged();
	}
	
	private void initializePadding() {
	    float density = getResources().getDisplayMetrics().density;
	    int padding = addPadding ? (int) (16 * density) : 0;
	    getListView().setPadding(padding, padding, padding, padding);
	}

    private void initializeHeaderAndFooter() {
        setListAdapter(null);
        if (hasHeaderAndFooter) {
            ListView list = getListView();

            LayoutInflater inflater = LayoutInflater.from(this);
            TextView header1 = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, list, false);
            header1.setText("First header");
            list.addHeaderView(header1);

            TextView header2 = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, list, false);
            header2.setText("Second header");
            list.addHeaderView(header2);

            TextView footer = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, list, false);
            footer.setText("Single footer");
            list.addFooterView(footer);
        }
        initializeAdapter();
    }

    @SuppressLint("NewApi")
    private void initializeAdapter() {
        getListView().setFastScrollEnabled(isFastScroll);
        if (isFastScroll) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                getListView().setFastScrollAlwaysVisible(true);
            }
            setListAdapter(new FastScrollAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1));
        } else {
            setListAdapter(new SimpleAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1));
        }
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(this, "Item: " + v.getTag() , Toast.LENGTH_SHORT).show();
    }

} public class RXActivity extends BaseActivity {

    @ViewId(R.id.btn_start)
    private Button btnStart;

    @ViewId(R.id.tv_message)
    private TextView tvMessage;

    private Context mContext;

    @Override
    protected void setListeners() {

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                click();
            }
        });
    }

    public void click() {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext("RXJava");
            }
        }).subscribeOn(Schedulers.io())
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        return "HELLO" + s.toUpperCase();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        tvMessage.setText(s);
                    }
                });
    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        mContext = this;

    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_rxjava;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ActivityCompat.finishAfterTransition(this);
    }
} public class ScrollviewActivity extends BaseActivity {

    @ViewId(R.id.detail_title)
    private TextView titleTextView;
    @ViewId(R.id.detail_body)
    private TextView detailBodyTextView;
    @ViewId(R.id.overscroll_view)
    private OverScrollView scrollView;

    @Override
    protected void setListeners() {

    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        titleTextView.setText("Hello World");

        scrollView.setOverScrollListener(new OverScrollView.OverScrollListener() {
            int translationThreshold = 120;
            @Override
            public boolean onOverScroll(int yDistance, boolean isReleased) {
                int cp = 1;
                if (yDistance < 0) {
                    cp = 3;
                }
                if (Math.abs(yDistance) > translationThreshold*cp) {
                    if (isReleased) {
                        onBackPressed();
                        return true;
                    }
                }
                return false;
            }
        });

        detailBodyTextView.setAlpha(0);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                detailBodyTextView.animate().alpha(1).start();
            }
        }, 500);
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_scrollview;
    }
} public class ServiceActivity extends BaseActivity {
    @ViewId(R.id.btn_start_service)
    private Button btn_start_service;
    @ViewId(R.id.btn_finish_service)
    private Button btn_finish_service;
    @ViewId(R.id.btn_bind_service)
    private Button btn_bind_service;
    @ViewId(R.id.btn_unbind_service)
    private Button btn_unbind_service;
    @ViewId(R.id.seekBar)
    private SeekBar seekBar;
    @ViewId(R.id.text_percent)
    private TextView textPercent;

    private Context mContext;
    private final String MYACTION = "updateSeekBar";

    private MService.MBinder mBinder;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mBinder = (MService.MBinder) iBinder;
            mBinder.startTask();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    private int curLoad = 0;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(MYACTION.equals(intent.getAction())){
                curLoad = intent.getIntExtra("CurrentLoading", 0);
                mHandler.sendMessage(mHandler.obtainMessage());
            }
        }
    };


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(curLoad < 0) {
                return;
            }
            seekBar.setProgress(curLoad);
            textPercent.setText(curLoad+"%");
            if (curLoad == 100) {
                unbindService(serviceConnection);
                Toast.makeText(mContext, "Download finished!", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MYACTION);
        registerReceiver(receiver, filter);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_start_service:
                Intent startServiceIntent = new Intent(this, MService.class);
                startService(startServiceIntent);
                break;
            case R.id.btn_finish_service:
                Intent stopServiceIntent = new Intent(this, MService.class);
                stopService(stopServiceIntent);
                break;
            case R.id.btn_bind_service:
                Intent bindIntent = new Intent(this, MService.class);
                bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbind_service:
                unbindService(serviceConnection);
                break;
            default:
                break;
        }
    }

    @Override
    protected void setListeners() {
        btn_start_service.setOnClickListener(this);
        btn_finish_service.setOnClickListener(this);
        btn_bind_service.setOnClickListener(this);
        btn_unbind_service.setOnClickListener(this);
    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        mContext = this;
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_service;
    }
} public class StickyActivity extends FragmentActivity {
    private String[] mTitles = new String[] { "简介", "评价", "相关" };
    private SimpleViewPagerIndicator mIndicator;
    private ViewPager mViewPager;
    private FragmentPagerAdapter mAdapter;
    private TabFragment[] mFragments = new TabFragment[mTitles.length];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sticky);

        initViews();
        initDatas();
        initEvents();
    }

    private void initEvents() {
        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
                mIndicator.scroll(position, positionOffset);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private void initDatas() {
        mIndicator.setTitles(mTitles);

        for (int i = 0; i < mTitles.length; i++) {
            mFragments[i] = (TabFragment) TabFragment.newInstance(mTitles[i]);
        }

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return mTitles.length;
            }

            @Override
            public Fragment getItem(int position) {
                return mFragments[position];
            }

        };

        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(0);
    }

    private void initViews() {
        mIndicator = (SimpleViewPagerIndicator) findViewById(R.id.id_stickynavlayout_indicator);
        mViewPager = (ViewPager) findViewById(R.id.id_stickynavlayout_viewpager);

    }

} public class SugarActivity extends BaseActivity {

    @ViewId(R.id.btn_add)
    private Button btnAdd;
    @ViewId(R.id.btn_query)
    private Button btnQuery;

    @ViewId(R.id.tv_contacts)
    private TextView tvContacts;

    @Override
    protected void setListeners() {
        btnAdd.setOnClickListener(this);
        btnQuery.setOnClickListener(this);
    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add:
                Contact contact = new Contact("abc", 10, "130-1111-2222");
                contact.save();
                break;
            case R.id.btn_query:
                List<Contact> contacts = Contact.listAll(Contact.class);
                String out = "";
                for (Contact c: contacts) {
                    out += c.getId() + c.getName() + ", " + c.getAge() + ", " + c.getPhone_number() + "\n";
                }
                tvContacts.setText(out);
        }
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_sugar;
    }
} public class SwipeBackDemoActivity extends SwipeBackActivity implements View.OnClickListener {
    //设置手机震动 0无震动
    private static final int VIBRATE_DURATION = 0;

    private int[] mBgColors;

    private static int mBgIndex = 0;

    private String mKeyTrackingMode;

    private RadioGroup mTrackingModeGroup;

    private SwipeBackLayout mSwipeBackLayout;

    private Toolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);
        findViews();
        changeActionBarColor();
        mKeyTrackingMode = getString(R.string.key_tracking_mode);
        mSwipeBackLayout = getSwipeBackLayout();

//        mSwipeBackLayout.setEdgeSize(getResources().getDisplayMetrics().widthPixels);
        mTrackingModeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int edgeFlag;
                switch (checkedId) {
                    case R.id.mode_left:
                        edgeFlag = SwipeBackLayout.EDGE_LEFT;
                        break;
                    case R.id.mode_right:
                        edgeFlag = SwipeBackLayout.EDGE_RIGHT;
                        break;
                    case R.id.mode_bottom:
                        edgeFlag = SwipeBackLayout.EDGE_BOTTOM;
                        break;
                    default:
                        edgeFlag = SwipeBackLayout.EDGE_ALL;
                }
                mSwipeBackLayout.setEdgeTrackingEnabled(edgeFlag);
                saveTrackingMode(edgeFlag);
            }
        });
        mSwipeBackLayout.addSwipeListener(new SwipeBackLayout.SwipeListener() {
            @Override
            public void onScrollStateChange(int state, float scrollPercent) {

            }

            @Override
            public void onEdgeTouch(int edgeFlag) {
                vibrate(VIBRATE_DURATION);
            }

            @Override
            public void onScrollOverThreshold() {
                vibrate(VIBRATE_DURATION);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        restoreTrackingMode();
    }

    private void saveTrackingMode(int flag) {
        PreferenceUtils.setPrefInt(getApplicationContext(), mKeyTrackingMode, flag);
    }

    private void restoreTrackingMode() {
        int flag = PreferenceUtils.getPrefInt(getApplicationContext(), mKeyTrackingMode,
                SwipeBackLayout.EDGE_LEFT);
        mSwipeBackLayout.setEdgeTrackingEnabled(flag);
        switch (flag) {
            case SwipeBackLayout.EDGE_LEFT:
                mTrackingModeGroup.check(R.id.mode_left);
                break;
            case SwipeBackLayout.EDGE_RIGHT:
                mTrackingModeGroup.check(R.id.mode_right);
                break;
            case SwipeBackLayout.EDGE_BOTTOM:
                mTrackingModeGroup.check(R.id.mode_bottom);
                break;
            case SwipeBackLayout.EDGE_ALL:
                mTrackingModeGroup.check(R.id.mode_all);
                break;
        }
    }

    private void changeActionBarColor() {
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getColors()[mBgIndex]));
        mBgIndex++;
        if (mBgIndex >= getColors().length) {
            mBgIndex = 0;
        }
    }

    private void findViews() {
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        findViewById(R.id.btn_start).setOnClickListener(this);
        findViewById(R.id.btn_finish).setOnClickListener(this);
        mTrackingModeGroup = (RadioGroup) findViewById(R.id.tracking_mode);
    }

    private int[] getColors() {
        if (mBgColors == null) {
            Resources resource = getResources();
            mBgColors = new int[] {
                    resource.getColor(R.color.androidColorA),
                    resource.getColor(R.color.androidColorB),
                    resource.getColor(R.color.androidColorC),
                    resource.getColor(R.color.androidColorD),
                    resource.getColor(R.color.androidColorE),
            };
        }
        return mBgColors;
    }

    private void vibrate(long duration) {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        long[] pattern = {
                0, duration
        };
        vibrator.vibrate(pattern, -1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:
                startActivity(new Intent(SwipeBackDemoActivity.this, SwipeBackDemoActivity.class));
                break;
            case R.id.btn_finish:
                scrollToFinishActivity();
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.swipe, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_github:
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("https://github.com/Issacw0ng/SwipeBackLayout"));
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

} public class TabHostActivity extends BaseFragmentActivity implements
        RadioGroup.OnCheckedChangeListener {

    @ViewId(R.id.tabhost)
    private FragmentTabHost mTabHost;

    @ViewId(R.id.tab_rg_menu)
    private RadioGroup tabGroup;

    @ViewId(R.id.tab_home)
    private RadioButton homeTab;

    @ViewId(R.id.tab_explore)
    private RadioButton exploreTab;

    @ViewId(R.id.tab_account)
    private RadioButton accountTab;

    private int curTabIndex = 0;
    private int preTabIndex = 0;

    private final Class<?>[] fragments = {HomeFragment.class, ExploreFragment.class, AccountFragment.class};

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tab_host;
    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls(Bundle savedInstanceState) {
        mTabHost.setup(this, getSupportFragmentManager(), R.id.lv_tab_content);
        int count = fragments.length;
        for (int i = 0; i < count; i++) {
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(i + "").setIndicator(i + "");
            mTabHost.addTab(tabSpec, fragments[i], null);
        }
    }

    @Override
    protected void setListeners() {
        tabGroup.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.tab_home:
                mTabHost.setCurrentTab(0);
                curTabIndex = 0;
                break;
            case R.id.tab_explore:
                mTabHost.setCurrentTab(1);
                preTabIndex = curTabIndex;
                curTabIndex = 1;
                break;
            case R.id.tab_account:
                mTabHost.setCurrentTab(2);
                curTabIndex = 2;
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {}
} public class ViewDragerActivity extends BaseActivity {

    @ViewId(R.id.tv_one)
    private TextView textView;

    @Override
    protected void setListeners() {

    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {

    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_view_drag;
    }
} public class ViewPagerActivity extends BaseActivity {

    @ViewId(R.id.tab_layout)
    private TabLayout tabLayout;
    @ViewId(R.id.viewpager)
    private ViewPager viewPager;

    MyFragmentPagerAdapter fragmentPagerAdapter;

    @Override
    protected void setListeners() {

    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        fragmentPagerAdapter = new MyFragmentPagerAdapter(this, getSupportFragmentManager());

        List<String> data = new ArrayList<>();
        data.add("Chat Room");
        data.add("Notification");

        fragmentPagerAdapter.setData(data);

        viewPager.setAdapter(fragmentPagerAdapter);
        viewPager.addOnPageChangeListener(new TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_viewpager;
    }
} public class ViewTouchActivity extends BaseActivity {

    private MyFrameLayout frameLayout;

    @Override
    protected void setListeners() {

    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        frameLayout = (MyFrameLayout) findViewById(R.id.frame_layout);

        TextView textView = new TextView(this);
        textView.setText("Hello");
        frameLayout.addView(textView);
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_view_touch;
    }
} public class VolleyActivity extends BaseActivity {

    private static String TAG = "VolleyActivity";

    @ViewId(R.id.btn_load)
    private Button btnLoad;
    @ViewId(R.id.btn_login)
    private Button btnLogin;
    @ViewId(R.id.btn_upload)
    private Button btnUpload;

    @ViewId(R.id.tv_content)
    private TextView tvContent;

    private RequestQueue requestQueue;

    private OkHttpClient client;

    private String url = "http://101.201.113.136:8080/api/account";

    private PersistentCookieStore cookieStore;
    private List<Cookie> cookieList = new ArrayList<>();
    private String token = "token";

    private boolean isLogin = false;

    @Override
    protected void setListeners() {
        btnLoad.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        btnUpload.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Headers headers = new Headers.Builder()
                .add("X-CSRF-TOKEN", token)
                .build();

        switch (v.getId()) {
            case R.id.btn_load:
                StringRequest stringRequest = new StringRequest(url,
                        new com.android.volley.Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                tvContent.setText(response);
                            }
                        },
                        new com.android.volley.Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        }){
                    @Override
                    public Map<String, String> getHeaders() {
                        HashMap<String, String> headers = new HashMap<>();
                        headers.put("X-CSRF-TOKEN", token);
                        headers.put("Content-Type", "application/json");
                        return headers;
                    }
                };
                requestQueue.add(stringRequest);

                Request request = new Request.Builder()
                        .url(url)
                        .headers(headers)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, okhttp3.Response response) throws IOException {
                        Log.d(TAG, "init: " + response.code() + response.body().string());
                    }
                });
                break;
            case R.id.btn_login:
                if (isLogin) {
                    return;
                }
                FormBody body = new FormBody.Builder()
                        .add("j_username", "admin")
                        .add("j_password", "admin")
                        .add("remember-me", "true")
                        .add("submit", "Login")
                        .build();
                Request request0 = new Request.Builder()
                        .url("http://101.201.113.136:8080/api/authentication")
                        .headers(headers)
                        .post(body)
                        .build();
                Call call0 = client.newCall(request0);
                call0.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d(TAG, "login: " + response.code() + response.body().string());
                        if (response.code() == 200) {
                            isLogin = true;
                        }
                    }
                });
                break;
            case R.id.btn_upload:
                File file = new File("sdcard/DCIM/test.jpg");
                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file", file.getName(), RequestBody.create(null, file))
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"another\";filename=\"another.dex\""),
                                RequestBody.create(MediaType.parse("application/octet-stream"), file))
                        .build();

                Request request1 = new Request.Builder()
                        .url("http://101.201.113.136:8080/api/uploadFile")
                        .headers(headers)
                        .post(requestBody)
                        .build();
                Call call1 = client.newCall(request1);
                call1.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d(TAG, "upload: " + response.code() + response.body().string());
                    }
                });

                break;
        }
    }

    @Override
    protected void readIntent() {

    }

    @Override
    protected void initControls() {
        cookieStore = new PersistentCookieStore(getApplicationContext());

        client = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        if (cookies.size() > 0) {
                            for (Cookie cookie : cookies) {
                                if (cookie.name().contains("TOKEN")) {
                                    if (!token.equals(cookie.value())) {
                                        token = cookie.value();
                                        Log.d(TAG, "update token: " + token);
                                    }
                                    break;
                                }
                            }
                        }
                        if (!isLogin) {
                            cookieList = cookies;
                            for (Cookie item : cookies) {
                                cookieStore.add(url, item);
                            }
                        }
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        cookieList = cookieStore.get(url);
                        return cookieList;
                    }
                })
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Response response = chain.proceed(request);
                        return response;
                    }
                })
                .build();

        requestQueue = Volley.newRequestQueue(this, new OkHttp3Stack(client));
    }

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_volley;
    }
} public class WeekPagerActivity extends ActionBarActivity implements WeekDayViewPager.DayScrollListener  {

  private final static String TAG = "WeekPagerActivity";

  @InjectView(R.id.view_pager)
  WeekDayViewPager mViewPagerContent;
  @InjectView(R.id.header_recycler_view)
  WeekRecyclerView mWeekRecyclerView;
  @InjectView(R.id.text_day_label)
  TextView mTextView;

  private SimplePagerAdapter mPagerAdapter;
  private WeekViewAdapter mWeekViewAdapter;
  private static final int OFFSCREEN_PAGE_LIMIT = 1;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_week_pager);
    ButterKnife.inject(this);
    setUpPager();
    setUpData();
  }

  private void setUpPager() {
    mPagerAdapter = new SimplePagerAdapter(getSupportFragmentManager());
    mViewPagerContent.setOffscreenPageLimit(OFFSCREEN_PAGE_LIMIT);
    mViewPagerContent.setAdapter(mPagerAdapter);
    mViewPagerContent.setWeekRecyclerView(mWeekRecyclerView);
    mViewPagerContent.setDayScrollListener(this);
    mWeekViewAdapter = new WeekViewAdapter(this, mViewPagerContent);
    mWeekViewAdapter.setTextNormalColor(getResources().getColor(android.R.color.darker_gray));
    mWeekRecyclerView.setAdapter(mWeekViewAdapter);
  }

  private void setUpData() {
    CalendarDay start = new CalendarDay(2016, 1, 1);
    CalendarDay end = new CalendarDay(2017, 12, 31);
    mWeekViewAdapter.setData(start, end, null);
    mPagerAdapter.setData(start, end);
    Calendar today = Calendar.getInstance();
    mViewPagerContent.setCurrentPosition(DayUtils.calculateDayPosition(mWeekViewAdapter.getFirstShowDay(),
            new CalendarDay(today.get(Calendar.YEAR), today.get(Calendar.MONTH) + 1, today.get(Calendar.DATE))));
  }

  @Override public void onDayPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    Calendar date = mPagerAdapter.getDatas().get(position).getCalendar();
    mTextView.setText(DayUtils.formatEnglishTime(date) + " " + ChineseCalendarGB.getChineseDay(date));
  }

  @Override public void onDayPageSelected(int position) {}

  @Override public void onDayPageScrollStateChanged(int state) {}

}
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.ActivityOptionsCompat;
import com.example.maguoqing.androiddemo.R;
import com.example.maguoqing.androiddemo.activity.DataBindingActivity;
import com.example.maguoqing.androiddemo.activity.LoginActivity;
import com.example.maguoqing.androiddemo.activity.MPanelViewActivity;
import com.example.maguoqing.androiddemo.activity.AnimationActivity;
import com.example.maguoqing.androiddemo.activity.AppBarDetailActivity;
import com.example.maguoqing.androiddemo.activity.AudioPlayerActivity;
import com.example.maguoqing.androiddemo.activity.CalendarMonthActivity;
import com.example.maguoqing.androiddemo.activity.IJKPlayerActivity;
import com.example.maguoqing.androiddemo.activity.ListActivity;
import com.example.maguoqing.androiddemo.activity.NotificationActivity;
import com.example.maguoqing.androiddemo.activity.PinnedSectionListActivity;
import com.example.maguoqing.androiddemo.activity.RXActivity;
import com.example.maguoqing.androiddemo.activity.ScrollviewActivity;
import com.example.maguoqing.androiddemo.activity.ServiceActivity;
import com.example.maguoqing.androiddemo.activity.StickyActivity;
import com.example.maguoqing.androiddemo.activity.SugarActivity;
import com.example.maguoqing.androiddemo.activity.SwipeBackDemoActivity;
import com.example.maguoqing.androiddemo.activity.TabHostActivity;
import com.example.maguoqing.androiddemo.activity.ViewDragerActivity;
import com.example.maguoqing.androiddemo.activity.ViewPagerActivity;
import com.example.maguoqing.androiddemo.activity.ViewTouchActivity;
import com.example.maguoqing.androiddemo.activity.VolleyActivity;
import com.example.maguoqing.androiddemo.activity.WeekPagerActivity;
package com.example.maguoqing.androiddemo.control;



/**
 * Created by Guoqing on 2015/12/18.
 */
public class IntentManager {

    public static void startListActivity (Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ListActivity.class);
        context.startActivity(intent);
    }

    public static void startPinnedActivity (Context context) {
        Intent intent = new Intent();
        intent.setClass(context, PinnedSectionListActivity.class);
        context.startActivity(intent);
    }

    public static void startStickyActivity (Context context) {
        Intent intent = new Intent();
        intent.setClass(context, StickyActivity.class);
        context.startActivity(intent);
    }

    public static void startAppBarActivity (Context context) {
        Intent intent = new Intent();
        intent.setClass(context, AppBarDetailActivity.class);
        context.startActivity(intent);
    }

    public static void startBottomTabActivity (Context context) {
        Intent intent = new Intent();
        intent.setClass(context, TabHostActivity.class);
        context.startActivity(intent);
    }

    public static void startScrollviewActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ScrollviewActivity.class);
        context.startActivity(intent);
    }

    public static void startSwipeBackActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, SwipeBackDemoActivity.class);
        context.startActivity(intent);
    }

    public static void startViewDragerActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ViewDragerActivity.class);
        context.startActivity(intent);
    }

    public static void startServiceActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ServiceActivity.class);
        context.startActivity(intent);
    }

    public static void startNotificationActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, NotificationActivity.class);
        context.startActivity(intent);
    }

    public static void startAnimationActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, AnimationActivity.class);
        context.startActivity(intent);
    }

    public static void startViewTouchActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ViewTouchActivity.class);
        context.startActivity(intent);
    }

    public static void startAudioPlayerActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, AudioPlayerActivity.class);
        context.startActivity(intent);
    }

    public static void startSugarActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, SugarActivity.class);
        context.startActivity(intent);
    }

    public static void startVolleyActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, VolleyActivity.class);
        context.startActivity(intent);
    }

    public static void startIJKPlayerActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, IJKPlayerActivity.class);
        context.startActivity(intent);
    }

    public static void startCalendarMonthActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, CalendarMonthActivity.class);
        context.startActivity(intent);
    }

    public static void startMPanelViewActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MPanelViewActivity.class);
        context.startActivity(intent);
    }

    public static void startWeekPagerActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, WeekPagerActivity.class);
        context.startActivity(intent);
    }

    public static void startLoginActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, LoginActivity.class);
        context.startActivity(intent);
    }

    public static void startDataBindingActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, DataBindingActivity.class);
        context.startActivity(intent);
    }

    public static void startRXJavaActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, RXActivity.class);
        context.startActivity(intent);
    }

    public static void startViewPagerActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ViewPagerActivity.class);