admin
2021-07-15 49982f5a1a305c0cc7da04735e1c604b802d2a22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package com.mugua.mgvideo.ui.main;
 
import java.io.File;
import java.io.IOException;
import java.util.List;
 
import org.apache.http.Header;
import org.json.JSONObject;
 
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.Settings;
 
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
 
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ScrollView;
import android.widget.TextView;
 
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lcjian.library.RetainViewFragment;
import com.lcjian.library.content.ConnectivityChangeHelper;
import com.lcjian.library.content.ConnectivityChangeHelper.OnConnectivityChangeListener;
import com.lcjian.library.util.cache.DiskLruCache;
import com.lcjian.library.util.common.StorageUtils;
import com.lcjian.library.util.common.StringUtils;
import com.mugua.mgvideo.R;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.viewpagerindicator.CirclePageIndicator;
import com.yeshi.base.utils.http.BasicTextHttpResponseHandler;
import com.mugua.mgvideo.MGVideoAPI;
import com.mugua.mgvideo.entity.HotVideoType;
import com.mugua.mgvideo.entity.Special;
import com.yeshi.base.entity.video.VideoType;
import com.mugua.mgvideo.ui.category.CategoryAdapter;
import com.mugua.mgvideo.ui.category.MVideosActivity;
import com.mugua.mgvideo.ui.category.StarAdapter;
import com.mugua.mgvideo.ui.discover.DiscoverTopAdapter;
import com.mugua.mgvideo.ui.discover.SpecificListActivity;
import com.mugua.mgvideo.ui.recommend.SearchActivity;
import com.yeshi.base.utils.RouteConstant;
 
public class CategoryFragment extends RetainViewFragment implements
        OnClickListener {
 
    private TextView tv_go_search;
 
    private TextView tv_no_network;
 
    private PullToRefreshScrollView ptsv_container;
 
    private GridView gv_video_category;
 
    private GridView gv_hot_stars;
 
    private DiskLruCache cache;
 
    private ConnectivityChangeHelper mChangeHelper;
 
    private List<String> hotSearchs = null;
 
    private ViewPager vp_theme;
 
    private CirclePageIndicator indicator_theme;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            cache = DiskLruCache.open(
                    new File(StorageUtils.getCacheDirectory(getActivity())
                            .toString(), "http"), getVersionNum(getActivity()),
                    1, 1024 * 1024);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public int getContentResource() {
        return R.layout.category_fragment;
    }
 
    @Override
    public void onCreateView(View contentView, Bundle savedInstanceState) {
 
        tv_no_network = (TextView) contentView.findViewById(R.id.tv_no_network);
        tv_no_network.setOnClickListener(this);
        vp_theme = (ViewPager) contentView.findViewById(R.id.vp_discover);
        vp_theme.setAdapter(new DiscoverTopAdapter(null, getActivity()
                .getApplicationContext()));
        indicator_theme = (CirclePageIndicator) contentView
                .findViewById(R.id.indicator_discover);
        indicator_theme.setViewPager(vp_theme);
        contentView.findViewById(R.id.tv_collection_more).setOnClickListener(
                this);
        mChangeHelper = new ConnectivityChangeHelper(getActivity(),
                new OnConnectivityChangeListener() {
 
                    @Override
                    public void onNetworkUnAvailable() {
                        tv_no_network.setVisibility(View.VISIBLE);
                    }
 
                    @Override
                    public void onWiFiAvailable() {
                        tv_no_network.setVisibility(View.GONE);
                    }
 
                    @Override
                    public void onMobileAvailable() {
                        tv_no_network.setVisibility(View.GONE);
                    }
                });
 
        tv_go_search = (TextView) contentView.findViewById(R.id.tv_go_search);
 
        ptsv_container = (PullToRefreshScrollView) contentView
                .findViewById(R.id.ptsv_container);
        gv_video_category = (GridView) contentView
                .findViewById(R.id.gv_video_category);
        gv_hot_stars = (GridView) contentView.findViewById(R.id.gv_hot_stars);
        tv_go_search.setOnClickListener(this);
        tv_go_search.setOnTouchListener(new OnTouchListener() {
 
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // getCompoundDrawables() 可以获取一个长度为4的数组,
                // 存放drawableLeft,Right,Top,Bottom四个图片资源对象
                // index=2 表示的是 drawableRight 图片资源对象
                Drawable drawable = tv_go_search.getCompoundDrawables()[2];
                if (drawable == null)
                    return false;
 
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
 
                // drawable.getIntrinsicWidth() 获取drawable资源图片呈现的宽度
                if (event.getX() > tv_go_search.getWidth()
                        - tv_go_search.getPaddingRight()
                        - drawable.getIntrinsicWidth()) {
                    if (!StringUtils.isEmpty(tv_go_search.getText().toString())) {
                        ARouter.getInstance().build(RouteConstant.PATH_VIDEO_SEARCH_RESULT).withString("key", tv_go_search.getText() + "").navigation();
                    } else {
                        Intent intent = new Intent(getActivity(),
                                SearchActivity.class);
                        intent.putExtra("value", tv_go_search.getText()
                                .toString());
                        startActivity(intent);
                    }
 
                } else {
                    Intent intent = new Intent(getActivity(),
                            SearchActivity.class);
                    intent.putExtra("value", tv_go_search.getText().toString());
                    startActivity(intent);
                }
                return true;
            }
 
        });
 
        // gv_video_category.setOnItemClickListener(new OnItemClickListener() {
        //
        // @Override
        // public void onItemClick(AdapterView<?> parent, View view,
        // int position, long id) {
        // if (parent.getItemAtPosition(position) != null) {
        // VideoType videoType = (VideoType) parent
        // .getItemAtPosition(position);
        // if (videoType.getId().contains("1111")) {
        // Intent intent = new Intent(parent.getContext(),
        // VideosLiveActivity.class);
        // intent.putExtra("video_type", videoType.getId());
        // intent.putExtra("title", videoType.getName());
        // startActivity(intent);
        // } else {
        // Intent intent = new Intent(parent.getContext(),
        // VideosActivity.class);
        // intent.putExtra("video_type", videoType.getId());
        // intent.putExtra("title", videoType.getName());
        // startActivity(intent);
        // }
        // }
        // }
        // });
        gv_hot_stars.setOnItemClickListener(new OnItemClickListener() {
 
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                HotVideoType hotStar = (HotVideoType) parent
                        .getItemAtPosition(position);
                Intent intent = new Intent(parent.getContext(),
                        MVideosActivity.class);
                intent.putExtra("video_type", hotStar.getType());
                startActivity(intent);
            }
        });
 
        ptsv_container
                .setOnRefreshListener(new OnRefreshListener<ScrollView>() {
 
                    @Override
                    public void onRefresh(
                            PullToRefreshBase<ScrollView> refreshView) {
                        vp_theme.setCurrentItem(0, true);
                        getCategories();
                        getHotStars();
                        getHomeAd();
                    }
                });
 
        ptsv_container.post(new Runnable() {
 
            @Override
            public void run() {
                if (cache != null) {
                    {
                        DiskLruCache.Snapshot snapshot = null;
                        try {
                            snapshot = cache.get(getKey("getCategories"));
                            if (snapshot != null) {
                                Gson gson = new GsonBuilder()
                                        .setFieldNamingPolicy(
                                                FieldNamingPolicy.UPPER_CAMEL_CASE)
                                        .create();
                                List<VideoType> categories = gson.fromJson(
                                        snapshot.getString(0),
                                        new TypeToken<List<VideoType>>() {
                                        }.getType());
                                gv_video_category
                                        .setAdapter(new CategoryAdapter(
                                                categories, getActivity()));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (snapshot != null) {
                                snapshot.close();
                            }
                        }
                    }
                    {
                        DiskLruCache.Snapshot snapshot = null;
                        try {
                            snapshot = cache.get(getKey("getHotStars"));
                            if (snapshot != null) {
                                Gson gson = new GsonBuilder()
                                        .setFieldNamingPolicy(
                                                FieldNamingPolicy.UPPER_CAMEL_CASE)
                                        .create();
                                List<HotVideoType> hotStars = gson.fromJson(
                                        snapshot.getString(0),
                                        new TypeToken<List<HotVideoType>>() {
                                        }.getType());
                                gv_hot_stars.setAdapter(new StarAdapter(
                                        hotStars));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (snapshot != null) {
                                snapshot.close();
                            }
                        }
                    }
                }
            }
        });
        // if (BeibeiVideoApplication.showAd) {
        // initAdvertisement();
        // }
        ptsv_container.postDelayed(new Runnable() {
 
            @Override
            public void run() {
                ptsv_container.setRefreshing();
            }
        }, 200);
 
        getHotSearch();
        getHomeAd();
    }
 
    private Runnable mAutoScroller = new Runnable() {
 
        @Override
        public void run() {
            PagerAdapter adapter = vp_theme.getAdapter();
            if (adapter != null && adapter.getCount() != 0) {
                vp_theme.setCurrentItem((vp_theme.getCurrentItem() + 1)
                        % adapter.getCount(), true);
            }
            vp_theme.postDelayed(this, 5000);
        }
    };
 
    @Override
    public void onResume() {
        super.onResume();
        indicator_theme.setViewPager(vp_theme);
        vp_theme.postDelayed(mAutoScroller, 2000);
        mChangeHelper.registerReceiver();
        initHotSearch();
    }
 
    @Override
    public void onPause() {
        super.onPause();
        vp_theme.removeCallbacks(mAutoScroller);
        mChangeHelper.unregisterReceiver();
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
 
    private String getKey(String method) {
        return new Md5FileNameGenerator().generate(method);
    }
 
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_go_search: {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
            break;
            case R.id.tv_no_network: {
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
            break;
            case R.id.tv_collection_more:
                startActivity(new Intent(tv_no_network.getContext(),
                        SpecificListActivity.class));
                break;
            default:
                break;
        }
    }
 
    private void initHotSearch() {
        if (hotSearchs != null && hotSearchs.size() > 0) {
            int count = (int) (hotSearchs.size() * Math.random());
            if (count > hotSearchs.size() - 1) {
                count = hotSearchs.size() - 1;
            }
            tv_go_search.setText(hotSearchs.get(count));
        }
    }
 
    /**
     * 获取热门搜索
     */
    private void getHotSearch() {
        if (getActivity() == null)
            return;
        SharedPreferences preferences = getActivity().getSharedPreferences(
                "user", Context.MODE_PRIVATE);
        String uid = preferences.getString("uid", "");
        MGVideoAPI.getHotSearch(getActivity(), uid,
                new BasicTextHttpResponseHandler() {
 
                    @Override
                    public void onSuccessPerfect(int statusCode,
                                                 Header[] headers, JSONObject jsonObject)
                            throws Exception {
                        if (jsonObject.getBoolean("IsPost")) {
                            Gson gson = new GsonBuilder().setFieldNamingPolicy(
                                    FieldNamingPolicy.UPPER_CAMEL_CASE)
                                    .create();
                            hotSearchs = gson.fromJson(jsonObject
                                    .getJSONObject("Data").getJSONArray("data")
                                    .toString(), new TypeToken<List<String>>() {
                            }.getType());
                            initHotSearch();
                        }
                    }
                });
    }
 
    private void getCategories() {
        if (getActivity() == null)
            return;
        SharedPreferences preferences = getActivity().getSharedPreferences(
                "user", Context.MODE_PRIVATE);
        String uid = preferences.getString("uid", "");
        MGVideoAPI.getClass(getActivity(), uid,
                new BasicTextHttpResponseHandler() {
 
                    @Override
                    public void onSuccessPerfect(int statusCode,
                                                 Header[] headers, JSONObject jsonObject)
                            throws Exception {
                        if (jsonObject.getBoolean("IsPost")) {
                            Gson gson = new GsonBuilder().setFieldNamingPolicy(
                                    FieldNamingPolicy.UPPER_CAMEL_CASE)
                                    .create();
                            List<VideoType> categories = gson.fromJson(
                                    jsonObject.getJSONObject("Data")
                                            .getJSONArray("data").toString(),
                                    new TypeToken<List<VideoType>>() {
                                    }.getType());
                            gv_video_category.setAdapter(new CategoryAdapter(
                                    categories, getActivity()));
                            // cache.remove(getKey("getCategories"));
                            DiskLruCache.Editor editor = cache
                                    .edit(getKey("getCategories"));
                            editor.set(0, jsonObject.getJSONObject("Data")
                                    .getJSONArray("data").toString());
                            editor.commit();
                        }
                    }
 
                    @Override
                    public void onFinish() {
                        ptsv_container.onRefreshComplete();
                    }
                });
    }
 
    public static int getVersionNum(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return pi.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return 1;
        }
    }
 
    private void getHotStars() {
        if (getActivity() == null)
            return;
        SharedPreferences preferences = getActivity().getSharedPreferences(
                "user", Context.MODE_PRIVATE);
        String uid = preferences.getString("uid", "");
        MGVideoAPI.getHotStars(getActivity(), uid,
                new BasicTextHttpResponseHandler() {
 
                    @Override
                    public void onSuccessPerfect(int statusCode,
                                                 Header[] headers, JSONObject jsonObject)
                            throws Exception {
                        if (jsonObject.getBoolean("IsPost")) {
                            Gson gson = new GsonBuilder().setFieldNamingPolicy(
                                    FieldNamingPolicy.UPPER_CAMEL_CASE)
                                    .create();
                            List<HotVideoType> hotStars = gson.fromJson(
                                    jsonObject.getJSONObject("Data")
                                            .getJSONArray("data").toString(),
                                    new TypeToken<List<HotVideoType>>() {
                                    }.getType());
                            gv_hot_stars.setAdapter(new StarAdapter(hotStars));
 
                            DiskLruCache.Editor editor = cache
                                    .edit(getKey("getHotStars"));
                            editor.set(0, jsonObject.getJSONObject("Data")
                                    .getJSONArray("data").toString());
                            editor.commit();
                        }
                    }
 
                    @Override
                    public void onFinish() {
                        ptsv_container.onRefreshComplete();
                    }
                });
    }
 
    /**
     * 获取顶部可滑动Banner中的数据
     */
    private void getHomeAd() {
        SharedPreferences preferences = tv_no_network.getContext()
                .getSharedPreferences("user", Context.MODE_PRIVATE);
        String uid = preferences.getString("uid", "");
        MGVideoAPI.getDiscpverAd(tv_no_network.getContext(), uid,
                new BasicTextHttpResponseHandler() {
 
                    @Override
                    public void onSuccessPerfect(int statusCode,
                                                 Header[] headers, JSONObject jsonObject)
                            throws Exception {
                        if (jsonObject.getBoolean("IsPost")) {
                            Gson gson = new GsonBuilder()
                                    .setPrettyPrinting()
                                    .setFieldNamingPolicy(
                                            FieldNamingPolicy.UPPER_CAMEL_CASE)
                                    .create();
                            List<Special> homeAds = gson.fromJson(jsonObject
                                            .getJSONObject("Data").getJSONArray("data")
                                            .toString(),
                                    new TypeToken<List<Special>>() {
                                    }.getType());
                            vp_theme.setAdapter(new DiscoverTopAdapter(homeAds,
                                    getActivity().getApplicationContext()));
                        }
                    }
 
                    @Override
                    public void onFinish() {
                        ptsv_container.onRefreshComplete();
                    }
                });
    }
}