admin
2021-04-01 d27fa2154fe6c6b40048333e75ac11f1a3f5fac5
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
package com.weikou.beibeivideo.ui.recommend;
 
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
 
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lcjian.library.util.common.SoftKeyboardUtils;
import com.lcjian.library.util.common.StringUtils;
import com.qq.e.ads.cfg.VideoOption;
import com.qq.e.ads.nativ.NativeADUnifiedListener;
import com.qq.e.ads.nativ.NativeUnifiedAD;
import com.qq.e.ads.nativ.NativeUnifiedADData;
import com.qq.e.comm.util.AdError;
import com.weikou.beibeivideo.BasicTextHttpResponseHandler;
import com.weikou.beibeivideo.BeibeiVideoAPI;
import com.weikou.beibeivideo.R;
import com.weikou.beibeivideo.entity.VideoInfo;
import com.weikou.beibeivideo.entity.VideoType;
import com.weikou.beibeivideo.entity.ad.ExpressAdContainer;
import com.weikou.beibeivideo.entity.video.VideoContent;
import com.weikou.beibeivideo.ui.BaseActivity;
import com.weikou.beibeivideo.ui.video.SearchResultAdapter;
import com.weikou.beibeivideo.util.DimenUtils;
import com.weikou.beibeivideo.util.UmengEventUtil;
import com.weikou.beibeivideo.util.ad.ExpressAdManager;
import com.weikou.beibeivideo.util.ad.GDTConstant;
import com.weikou.beibeivideo.util.ad.manager.SearchResultAdManager;
import com.weikou.beibeivideo.util.ui.DividerItemDecoration;
import com.weikou.beibeivideo.util.ui.TopStatusSettings;
 
import org.apache.http.Header;
import org.json.JSONObject;
 
import java.util.ArrayList;
import java.util.List;
 
public class SearchResultActivity extends BaseActivity implements
        OnClickListener {
 
    private EditText et_search_key;
 
    private TextView tv_search_cancel;
 
    private RecyclerView rv_video_search;
 
    private List<VideoContent> mVideoInfos;
 
    private SearchResultAdapter adapter;
 
 
    private int mCurrentPage = 1;
 
    private String mCurrentType = "0";
 
    private String mCurrentKey;
 
    private boolean mFirst = true;
 
    private SwipeRefreshLayout rl_search_result;
 
    private ExpressAdManager expressAdManager;
 
    private boolean isLoad;
 
    private View loading;
 
    private LinearLayout ll_top_bar;
 
    List<VideoType> typeList;
 
    private LinearLayout ll_empty;
 
    private SearchSuggestFragment suggestFragment;
 
    private FrameLayout fl_suggest;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_result_activity);
        TopStatusSettings.setStatusViewAndDeepColor(this);
 
        suggestFragment = new SearchSuggestFragment();
 
        rl_search_result = findViewById(R.id.rl_search_result);
        et_search_key = findViewById(R.id.et_search_key);
        tv_search_cancel = findViewById(R.id.tv_search_cancel);
        rv_video_search = findViewById(R.id.rv_video_search);
        ll_top_bar = findViewById(R.id.ll_top_bar);
        ll_empty = findViewById(R.id.ll_empty);
        fl_suggest = findViewById(R.id.fl_suggest);
 
        tv_search_cancel.setOnClickListener(this);
        et_search_key.addTextChangedListener(new TextWatcher() {
 
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
 
            }
 
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
 
            }
 
            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    et_search_key.setCompoundDrawablesWithIntrinsicBounds(0, 0,
                            R.drawable.ic_clear, 0);
                } else {
                    et_search_key.setCompoundDrawablesWithIntrinsicBounds(0, 0,
                            0, 0);
                }
                if (mFirst) {
                    mFirst = false;
                } else {
                    suggestSearch(s != null ? s.toString() : null);
                }
            }
        });
 
        et_search_key.setOnTouchListener(new OnTouchListener() {
 
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // getCompoundDrawables() 可以获取一个长度为4的数组,
                // 存放drawableLeft,Right,Top,Bottom四个图片资源对象
                // index=2 表示的是 drawableRight 图片资源对象
                Drawable drawable = et_search_key.getCompoundDrawables()[2];
                if (drawable == null)
                    return false;
 
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
 
                // drawable.getIntrinsicWidth() 获取drawable资源图片呈现的宽度
                if (event.getX() > et_search_key.getWidth()
                        - et_search_key.getPaddingRight()
                        - drawable.getIntrinsicWidth()) {
                    et_search_key.setText("");
                }
                return false;
            }
        });
 
 
        et_search_key.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    startSearch();
                    return true;
                }
                return false;
            }
        });
 
 
        mCurrentKey = getIntent().getStringExtra("key");
        et_search_key.setText(mCurrentKey);
        et_search_key.setSelection(mCurrentKey.length());
        // et_search_key.setText(mCurrentKey);
 
        mVideoInfos = new ArrayList<>();
        rl_search_result.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 1;
                search(mCurrentKey, mCurrentType);
            }
        });
 
 
        rv_video_search.setLayoutManager(new MyLinearLayoutManager(getApplicationContext()));
        DividerItemDecoration decoration = new DividerItemDecoration();
        decoration.setSize(DimenUtils.dip2px(rv_video_search.getContext(), 15));
        rv_video_search.addItemDecoration(decoration);
 
        adapter = new SearchResultAdapter(this, mVideoInfos, new SearchResultAdapter.VideoAlbumNavClickListener() {
            @Override
            public void onNav(int p) {
                navClick(p);
            }
        });
        loading = LayoutInflater.from(this).inflate(R.layout.item_loading, null);
        loading.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        loading.setVisibility(View.GONE);
        adapter.setFooterView(loading);
 
        rv_video_search.setAdapter(adapter);
        rv_video_search.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int first = manager.findFirstVisibleItemPosition();
                int last = manager.findLastVisibleItemPosition();
                int total = manager.getItemCount();
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if ((!isLoad) && last == total - 1 && mVideoInfos.size() < 1000) {
                        if (mVideoInfos != null && mVideoInfos.size() > 0 && !rl_search_result.isRefreshing()) {//列表中有数据才能加载更多
                            mCurrentPage++;
                            isLoad = true;
                            loading.setVisibility(View.VISIBLE);
                            search(mCurrentKey, mCurrentType);
                        }
                    }
                }
            }
 
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, final int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
 
        ProgressBar pb = new ProgressBar(SearchResultActivity.this);
        rl_search_result.setRefreshing(true);
        search(mCurrentKey, mCurrentType);
//        loadAd();
    }
 
    private void startSearch() {
        if (StringUtils.isEmpty(et_search_key.getEditableText()
                .toString())) {
            mCurrentKey = et_search_key.getText().toString();
        } else {
            mCurrentKey = et_search_key.getEditableText().toString();
        }
        SoftKeyboardUtils.hideSoftInput(SearchResultActivity.this);
        mCurrentPage = 1;
        rl_search_result.setRefreshing(true);
        //清除顶部分类
        typeList = null;
        search(mCurrentKey, mCurrentType);
    }
 
 
    private void initTopBar() {
        int p = 0;
        ll_top_bar.removeAllViews();
        LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
        for (int i = 0; i < typeList.size(); i++) {
            final View view = inflater.inflate(R.layout.item_search_result_top_bar_content, null);
            TextView tv_name = view.findViewById(R.id.tv_name);
            tv_name.setText(typeList.get(i).getName());
            setTopBarSelect(tv_name, i == p);
            ll_top_bar.addView(view);
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
            params.rightMargin = DimenUtils.dip2px(getApplicationContext(), 17);
            params.leftMargin = DimenUtils.dip2px(getApplicationContext(), 10);
            view.setTag(i);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p = Integer.parseInt(view.getTag() + "");
                    navClick(p);
                }
            });
        }
    }
 
    private void navClick(int p) {
        if (typeList == null || typeList.size() <= p)
            return;
        selectTopBar(p);
        VideoType vt = typeList.get(p);
 
        if (StringUtils.isBlank(mCurrentType) || !mCurrentType.equalsIgnoreCase(vt.getId())) {
            mCurrentPage = 1;
            mCurrentType = vt.getId();
            rl_search_result.setRefreshing(true);
            search(mCurrentKey, mCurrentType);
        }
    }
 
    private void setTopBarSelect(TextView tv_name, boolean selected) {
        if (selected) {
            tv_name.setBackgroundResource(R.drawable.vpi__tab_selected_focused_holo);
            tv_name.setTextSize(19);
            tv_name.setTextColor(getResources().getColor(R.color.search_nav_highlight_text_color));
            tv_name.setPadding(0, 0, 0, DimenUtils.dip2px(getApplicationContext(), 5));
            tv_name.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        } else {
            tv_name.setBackground(null);
            tv_name.setTextSize(14);
            tv_name.setTextColor(getResources().getColor(R.color.nav_text_color));
            tv_name.setPadding(0, 0, 0, 0);
            tv_name.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        }
    }
 
    private void selectTopBar(int p) {
        for (int i = 0; i < ll_top_bar.getChildCount(); i++) {
            TextView tv = ll_top_bar.getChildAt(i).findViewById(R.id.tv_name);
            setTopBarSelect(tv, i == p);
        }
    }
 
 
    private void hiddenSuggestFragment() {
        fl_suggest.setVisibility(View.GONE);
        getSupportFragmentManager().beginTransaction().remove(suggestFragment).commitAllowingStateLoss();
    }
 
    private void showSuggestFragment(String key, List<String> list) {
        Bundle bundle = new Bundle();
        bundle.putString("key", key);
        bundle.putString("list", new Gson().toJson(list));
        fl_suggest.setVisibility(View.VISIBLE);
        suggestFragment.setItemClickListener(new SearchSuggestFragment.OnItemClickListener() {
            @Override
            public void onClick(String st) {
                mFirst = true;
                hiddenSuggestFragment();
                et_search_key.setText(st);
                startSearch();
            }
        });
 
        suggestFragment.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_suggest, suggestFragment).commitAllowingStateLoss();
    }
 
 
    private void suggestSearch(String key) {
        if (StringUtils.isEmpty(key)) {
            hiddenSuggestFragment();
        }
 
        SharedPreferences preferences = getSharedPreferences("user",
                Context.MODE_PRIVATE);
        String uid = preferences.getString("uid", "");
        BeibeiVideoAPI.suggestSearch(this, uid, key,
                new BasicTextHttpResponseHandler() {
 
                    @Override
                    public void onSuccessPerfect(int statusCode,
                                                 Header[] headers, JSONObject jsonObject)
                            throws Exception {
                        List<String> results = null;
                        if (jsonObject.getBoolean("IsPost")) {
                            Gson gson = new GsonBuilder().setFieldNamingPolicy(
                                    FieldNamingPolicy.UPPER_CAMEL_CASE)
                                    .create();
                            results = gson.fromJson(jsonObject
                                    .getJSONObject("Data").getJSONArray("data")
                                    .toString(), new TypeToken<List<String>>() {
                            }.getType());
 
 
//                            SuggestKeysAdapter adapter = new SuggestKeysAdapter(getApplicationContext(), results);
//                            et_search_key.setAdapter(adapter);
//                            adapter.notifyDataSetChanged();
                        }
 
                        if (results != null && results.size() > 0) {
                            showSuggestFragment(key, results);
                            suggestFragment.setData(key, results);
                        } else {
                            hiddenSuggestFragment();
                        }
 
                    }
                });
    }
 
    private synchronized void fillAD(List<ExpressAdContainer> adList) {
 
        //判断当前页面是否需要广告
        int albumCount = 0;
        if (mVideoInfos != null && mVideoInfos.size() > 0)
            for (int i = 0; i < mVideoInfos.size(); i++) {
                VideoContent vc = mVideoInfos.get(i);
                if (vc.getType() == VideoContent.TYPE_AD) {
                    //更新广告
                    vc.setAd(adList.get(0));
                    adapter.notifyItemChanged(i);
                    return;
                } else if (vc.getVideo().getShowType() == 1) {
                    albumCount++;
                }
            }
 
        if (albumCount >= 2) {
            VideoContent videoContent = VideoContent.createAdContent(adList.get(0));
            mVideoInfos.add(2, videoContent);
            adapter.notifyItemInserted(2);
        }
 
    }
 
    //拉取2.0的自渲染广告
    private void loadAd() {
        String pid = GDTConstant.PID_2_SEARCH_RESULT_ALBUM;
        NativeUnifiedAD mAdManager = new NativeUnifiedAD(this, pid, new NativeADUnifiedListener() {
 
            @Override
            public void onNoAD(AdError adError) {
 
            }
 
            @Override
            public void onADLoaded(List<NativeUnifiedADData> list) {
                if (list != null && list.size() > 0) {
                    List<ExpressAdContainer> adList = new ArrayList<>();
                    adList.add(new ExpressAdContainer(list.get(0)));
                    fillAD(adList);
                }
            }
        });
        mAdManager.setVideoPlayPolicy(VideoOption.VideoPlayPolicy.AUTO);
        mAdManager.loadData(1);
    }
 
//    private void loadAd() {
//        ExpressAdContainer ad = SearchResultAdManager.getInstance(getApplicationContext()).consumeAD();
//        if (ad == null) {
//            SearchResultAdManager.getInstance(getApplicationContext()).loadAD(1, new ExpressAdManager.IAdLoadListener() {
//                @Override
//                public void onSuccess(List<ExpressAdContainer> adList) {
//                    fillAD(adList);
//                }
//            });
//        } else {
//            List<ExpressAdContainer> adList = new ArrayList<>();
//            adList.add(ad);
//            fillAD(adList);
//        }
//        //加载下一个需要的广告
//        SearchResultAdManager.getInstance(getApplicationContext()).autoLoadAd();
//    }
 
 
    private void search(String key, String videoType) {
 
        UmengEventUtil.search(getApplicationContext(), videoType);
 
        SharedPreferences preferences = getSharedPreferences("user",
                Context.MODE_PRIVATE);
        String uid = preferences.getString("uid", "");
        BeibeiVideoAPI.search(this, uid, key, videoType,
                String.valueOf(mCurrentPage),
                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();
                            JSONObject rootData = jsonObject.getJSONObject("Data");
                            List<VideoInfo> videoInfos = gson.fromJson(
 
                                    rootData.getJSONArray("data").toString(),
                                    new TypeToken<List<VideoInfo>>() {
                                    }.getType());
 
                            //设置导航栏
                            if (rootData.opt("typeList") != null) {
                                if (typeList == null) {
                                    typeList = gson.fromJson(
                                            rootData
                                                    .getJSONArray("typeList").toString(),
                                            new TypeToken<List<VideoType>>() {
                                            }.getType());
                                    initTopBar();
                                }
                            }
 
                            List<VideoContent> videoContentList = new ArrayList<>();
                            for (VideoInfo video : videoInfos) {
                                videoContentList.add(VideoContent.createVideoContent(video));
                            }
 
 
                            //记录当前的广告信息
                            VideoContent adContent = null;
                            int adContentP = -1;
                            if (mCurrentPage <= 1) {
                                for (int i = 0; i < mVideoInfos.size(); i++) {
                                    if (mVideoInfos.get(i).getType() == VideoContent.TYPE_AD) {
                                        adContent = mVideoInfos.get(i);
                                        adContentP = i;
                                    }
                                }
                                mVideoInfos.clear();
                            }
 
                            mVideoInfos.addAll(videoContentList);
                            if (adContent != null && mVideoInfos.size() >= adContentP) {
                                mVideoInfos.add(adContentP, adContent);
                            }
                            adapter.notifyDataSetChanged();
 
                            if (mVideoInfos != null && mVideoInfos.size() > 0) {
                                //有值
                                ll_empty.setVisibility(View.GONE);
                                rl_search_result.setVisibility(View.VISIBLE);
                            } else {
                                //无值
                                ll_empty.setVisibility(View.VISIBLE);
                                rl_search_result.setVisibility(View.GONE);
                            }
 
                            if (mCurrentPage == 1) {
                                loadAd();
                            }
                        }
                    }
 
                    @Override
                    public void onFinish() {
                        isLoad = false;
                        rl_search_result.setRefreshing(false);
                        loading.setVisibility(View.GONE);
                    }
                });
 
        saveHistory(key);
    }
 
    @Override
    public void onResume() {
        super.onResume();
    }
 
    @Override
    public void onPause() {
        super.onPause();
    }
 
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_search_cancel: {
                if (fl_suggest.getVisibility() == View.VISIBLE) {
                    hiddenSuggestFragment();
                } else {
                    finish();
                }
            }
            break;
            case R.id.tv_top_bar_left:
                finish();
                break;
            default:
                break;
        }
    }
 
    public void saveHistory(String key) {
        // 获取搜索框信息
        SharedPreferences historySp = getSharedPreferences("search_history",
                Context.MODE_PRIVATE);
        String history = historySp.getString("history", "");
 
        key = key.replace(",", "");
        String[] historyArray = history.split(",");
        List<String> temps = new ArrayList<String>();
        for (int i = 0; i < historyArray.length && i < 20; i++) {
            if (!TextUtils.isEmpty(historyArray[i])
                    && !historyArray[i].equals(key)) {
                temps.add(historyArray[i]);
            }
        }
        temps.add(key);
        StringBuilder builder = new StringBuilder();
        for (String str : temps) {
            builder.append(str).append(",");
        }
        historySp
                .edit()
                .putString("history",
                        builder.substring(0, builder.length() - 1)).commit();
    }
 
 
    class MyLinearLayoutManager extends LinearLayoutManager {
 
        public MyLinearLayoutManager(Context context) {
            super(context);
        }
 
        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }
}