package com.haicaojie.android.ui.main;
|
|
import android.content.Context;
|
import android.content.Intent;
|
import android.content.pm.PackageInfo;
|
import android.content.pm.PackageManager;
|
import android.graphics.drawable.Drawable;
|
import android.os.Build;
|
import android.os.Bundle;
|
import android.provider.Settings;
|
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.util.Log;
|
import android.view.KeyEvent;
|
import android.view.LayoutInflater;
|
import android.view.MotionEvent;
|
import android.view.View;
|
import android.view.Window;
|
import android.view.WindowManager;
|
import android.view.inputmethod.EditorInfo;
|
import android.widget.ArrayAdapter;
|
import android.widget.AutoCompleteTextView;
|
import android.widget.ImageView;
|
import android.widget.LinearLayout;
|
import android.widget.TextView;
|
import android.widget.Toast;
|
|
import com.google.gson.Gson;
|
import com.google.gson.GsonBuilder;
|
import com.google.gson.reflect.TypeToken;
|
import com.haicaojie.android.entity.HomeBanner;
|
import com.lcjian.library.RetainViewFragment;
|
import com.lcjian.library.content.ConnectivityChangeHelper;
|
import com.lcjian.library.recyclerview.DividerItemDecoration;
|
import com.lcjian.library.util.NetUtils;
|
import com.lcjian.library.util.SingleToast;
|
import com.lcjian.library.util.cache.DiskLruCache;
|
import com.lcjian.library.util.common.DimenUtils;
|
import com.lcjian.library.util.common.StorageUtils;
|
import com.lcjian.library.util.common.StringUtils;
|
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
|
import com.umeng.analytics.MobclickAgent;
|
import com.haicaojie.android.BasicTextHttpResponseHandler;
|
import com.haicaojie.android.R;
|
import com.haicaojie.android.ShoppingApi;
|
import com.haicaojie.android.entity.TaoBaoGoodsBrief;
|
import com.haicaojie.android.ui.category.CouponRecyclerAdapter;
|
import com.haicaojie.android.ui.recommend.SearchResultActivity;
|
|
import org.apache.http.Header;
|
import org.json.JSONArray;
|
import org.json.JSONObject;
|
|
import java.io.File;
|
import java.io.IOException;
|
import java.util.ArrayList;
|
import java.util.List;
|
|
/**
|
* Created by weikou2015 on 2017/2/20.
|
* 主页--优惠券
|
*/
|
|
public class CouponFragment extends RetainViewFragment implements View.OnClickListener {
|
private SwipeRefreshLayout srl_second_category;
|
private RecyclerView lv_second_category;
|
private LinearLayout ll_no_net, ll_no_data, ll_request_failture;
|
|
private CouponRecyclerAdapter adapter;
|
private List<TaoBaoGoodsBrief> mList = new ArrayList<>();
|
private int page = 1;
|
private ImageView iv_slid_top;
|
private int count = 999;
|
private boolean isLoad = true;
|
private boolean upLoad = false;
|
private boolean haveCache = false;
|
View bottom;
|
TextView tv_loading;
|
private AutoCompleteTextView et_search;
|
private View v_status_bar;
|
private DiskLruCache cache;
|
private ConnectivityChangeHelper mChangeHelper;
|
|
@Override
|
public int getContentResource() {
|
return R.layout.fragment_recommend_category;
|
}
|
|
@Override
|
public void onCreateView(View contentView, Bundle savedInstanceState) {
|
v_status_bar = contentView.findViewById(R.id.v_status_bar);
|
/*
|
* 计算状态栏高度并设置
|
*/
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
|
Window window = getActivity().getWindow();
|
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
|
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
|
int result = 0;
|
int resourceId = getResources().getIdentifier("status_bar_height",
|
"dimen", "android");
|
if (resourceId > 0) {
|
result = getResources().getDimensionPixelSize(resourceId);
|
}
|
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
|
result);
|
v_status_bar.setLayoutParams(params);
|
} else {
|
v_status_bar.setVisibility(View.GONE);
|
}
|
srl_second_category = (SwipeRefreshLayout) contentView.findViewById(R.id.srl_second_category);
|
lv_second_category = (RecyclerView) contentView.findViewById(R.id.lv_second_category);
|
iv_slid_top = (ImageView) contentView.findViewById(R.id.iv_slid_top);
|
et_search = (AutoCompleteTextView) contentView.findViewById(R.id.et_search);
|
et_search.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_clear, 0);
|
iv_slid_top.setOnClickListener(this);
|
contentView.findViewById(R.id.tv_category_search).setOnClickListener(this);
|
|
lv_second_category.setLayoutManager(new LinearLayoutManager(getContext()));
|
DividerItemDecoration vDivider = new DividerItemDecoration(DividerItemDecoration.VERTICAL);
|
vDivider.setColor(0xffeeeeee);
|
vDivider.setSize(DimenUtils.dip2px(getContext(), 2));
|
lv_second_category.addItemDecoration(vDivider);
|
adapter = new CouponRecyclerAdapter(lv_second_category.getContext(), mList);
|
|
bottom = LayoutInflater.from(getContext()).inflate(R.layout.item_recommend_bottom, null);
|
adapter.addFooterView(bottom);
|
tv_loading = (TextView) bottom.findViewById(R.id.tv_loading);
|
bottom.setVisibility(View.GONE);
|
// tv_update_time = (TextView) top_view.findViewById(R.id.tv_update_time);
|
adapter.addHeaderView(new View(getContext()));
|
lv_second_category.setAdapter(adapter);
|
srl_second_category.setRefreshing(true);
|
|
ll_no_net = (LinearLayout) contentView.findViewById(R.id.ll_no_net);
|
ll_no_data = (LinearLayout) contentView.findViewById(R.id.ll_no_data);
|
ll_request_failture = (LinearLayout) contentView.findViewById(R.id.ll_request_failture);
|
contentView.findViewById(R.id.iv_net_setting).setOnClickListener(this);
|
contentView.findViewById(R.id.tv_refresh).setOnClickListener(this);
|
|
mChangeHelper = new ConnectivityChangeHelper(lv_second_category.getContext(),
|
new ConnectivityChangeHelper.OnConnectivityChangeListener() {
|
|
@Override
|
public void onNetworkUnAvailable() {
|
}
|
|
@Override
|
public void onNetworkAvailable() {
|
requestState(0);
|
if (mList.size() == 0 || haveCache) {
|
getGoodsList();
|
}
|
}
|
});
|
|
srl_second_category.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
|
@Override
|
public void onRefresh() {
|
page = 1;
|
tv_loading.setText("加载中...");
|
getGoodsList();
|
}
|
});
|
lv_second_category.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 (first == 0) {
|
iv_slid_top.setVisibility(View.GONE);
|
}
|
if (last == total - 1 && mList.size() < count && isLoad) {
|
page++;
|
isLoad = false;
|
getGoodsList();
|
} else if (mList.size() >= count && last >= mList.size() - 1 && upLoad) {
|
if (NetUtils.getNetworkState(getContext()).equalsIgnoreCase(NetUtils.NETWORK_NONE)) {
|
SingleToast.showToast(getContext(), "网络未连接,请检测网络设置");
|
} else {
|
SingleToast.showToast(getContext(), "没有更多了");
|
}
|
}
|
} else {
|
iv_slid_top.setVisibility(View.GONE);
|
}
|
}
|
|
@Override
|
public void onScrolled(RecyclerView recyclerView, int dx, final int dy) {
|
super.onScrolled(recyclerView, dx, dy);
|
if (Math.abs(dy) > 10) {
|
if (dy > 0) {
|
upLoad = true;
|
iv_slid_top.setVisibility(View.GONE);
|
} else {
|
upLoad = false;
|
iv_slid_top.setVisibility(View.VISIBLE);
|
}
|
}
|
}
|
});
|
et_search.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) {
|
|
}
|
|
@Override
|
public void afterTextChanged(Editable s) {
|
if (!TextUtils.isEmpty(s.toString())) {
|
et_search.setHint("");
|
// setHistory();
|
suggestSearch(s.toString());
|
}
|
}
|
});
|
et_search.setOnTouchListener(new View.OnTouchListener() {
|
@Override
|
public boolean onTouch(View view, MotionEvent event) {
|
Drawable drawable = et_search.getCompoundDrawables()[2];
|
if (drawable == null)
|
return false;
|
|
if (event.getAction() != MotionEvent.ACTION_UP)
|
return false;
|
|
// drawable.getIntrinsicWidth() 获取drawable资源图片呈现的宽度
|
if (event.getX() > et_search.getWidth()
|
- et_search.getPaddingRight()
|
- drawable.getIntrinsicWidth()) {
|
et_search.setText("");
|
et_search.setHint("");
|
}
|
// et_search.setHint("");
|
// Log.i("mResult", et_search.getHint().toString());
|
// if (StringUtils.isBlank(et_search.getText().toString())) {
|
// et_search.setText(" ");
|
// setHistory();
|
// }
|
return false;
|
}
|
});
|
et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
|
|
@Override
|
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
|
if ((arg1 == EditorInfo.IME_ACTION_SEARCH || arg1 == EditorInfo.IME_ACTION_DONE)
|
&& !StringUtils.isEmpty(et_search.getText()
|
.toString())) {
|
Intent intent = new Intent(getContext(),
|
SearchResultActivity.class);
|
intent.putExtra("content", et_search.getText().toString());
|
intent.putExtra("type", "coupon");
|
startActivity(intent);
|
return true;
|
} else if ((arg1 == EditorInfo.IME_ACTION_SEARCH || arg1 == EditorInfo.IME_ACTION_DONE)
|
&& !StringUtils.isEmpty(et_search.getHint()
|
.toString())) {
|
Intent intent = new Intent(getContext(),
|
SearchResultActivity.class);
|
intent.putExtra("content", et_search.getHint().toString());
|
intent.putExtra("type", "coupon");
|
startActivity(intent);
|
return true;
|
}
|
return false;
|
}
|
});
|
|
if (cache != null) {
|
DiskLruCache.Snapshot snapshot = null;
|
try {
|
snapshot = cache.get(getKey("getCouponRecommendGoods"));
|
if (snapshot != null) {
|
Gson gson = new GsonBuilder().serializeNulls().create();
|
List<TaoBaoGoodsBrief> list = gson.fromJson(
|
snapshot.getString(0),
|
new TypeToken<List<TaoBaoGoodsBrief>>() {
|
}.getType());
|
mList.addAll(list);
|
adapter.notifyDataSetChanged();
|
haveCache = true;
|
requestState(0);
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
if (snapshot != null) {
|
snapshot.close();
|
}
|
}
|
}
|
|
getGoodsList();
|
}
|
|
private void suggestSearch(String key) {
|
ShoppingApi.getSuggestSearch(getContext(), key, new BasicTextHttpResponseHandler() {
|
@Override
|
public void onSuccessPerfect(int statusCode, Header[] headers, JSONObject jsonObject) throws Exception {
|
if (jsonObject.optString("code").equalsIgnoreCase("0")) {
|
Gson gson = new GsonBuilder().serializeNulls().create();
|
List<String> list = gson.fromJson(
|
jsonObject.optJSONArray("data").toString(),
|
new TypeToken<List<String>>() {
|
}.getType());
|
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(),
|
android.R.layout.simple_list_item_1,
|
list);
|
et_search.setAdapter(adapter);
|
adapter.notifyDataSetChanged();
|
}
|
}
|
|
@Override
|
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
|
super.onFailure(statusCode, headers, responseString, throwable);
|
}
|
});
|
}
|
|
@Override
|
public void onCreate(Bundle savedInstanceState) {
|
super.onCreate(savedInstanceState);
|
try {
|
cache = DiskLruCache.open(
|
new File(StorageUtils.getCacheDirectory(getContext())
|
.toString(), "http"), getVersionNum(getContext()),
|
1, 1024 * 1024);
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
private int getVersionNum(Context context) {
|
try {
|
PackageInfo pi = context.getPackageManager().getPackageInfo(
|
context.getPackageName(), 0);
|
return pi.versionCode;
|
} catch (PackageManager.NameNotFoundException e) {
|
e.printStackTrace();
|
return 1;
|
}
|
}
|
|
@Override
|
public void onResume() {
|
super.onResume();
|
|
//设置状态栏文字颜色及图标为深色
|
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
|
mChangeHelper.registerReceiver();
|
MobclickAgent.onPageStart("分类详情页");
|
}
|
|
@Override
|
public void onPause() {
|
super.onPause();
|
mChangeHelper.unregisterReceiver();
|
MobclickAgent.onPageEnd("分类详情页");
|
}
|
|
|
private void getGoodsList() {
|
ShoppingApi.getCouponRecommendGoods(lv_second_category.getContext(), page + "", new BasicTextHttpResponseHandler() {
|
@Override
|
public void onStart() {
|
super.onStart();
|
if (page > 0) {
|
bottom.setVisibility(View.VISIBLE);
|
} else {
|
bottom.setVisibility(View.GONE);
|
}
|
}
|
|
@Override
|
public void onFinish() {
|
super.onFinish();
|
bottom.setVisibility(View.GONE);
|
srl_second_category.setRefreshing(false);
|
}
|
|
@Override
|
public void onSuccessPerfect(int statusCode, Header[] headers, JSONObject jsonObject) throws Exception {
|
haveCache = false;
|
if (jsonObject.optString("code").equalsIgnoreCase("0")) {
|
Gson gson = new GsonBuilder().serializeNulls().create();
|
List<TaoBaoGoodsBrief> list = gson.fromJson(
|
jsonObject.optJSONObject("data").optJSONArray("taoBaoCoupons").toString(),
|
new TypeToken<List<TaoBaoGoodsBrief>>() {
|
}.getType());
|
if (page == 1)
|
mList.clear();
|
mList.addAll(list);
|
adapter.notifyDataSetChanged();
|
isLoad = true;
|
count = Integer.parseInt(jsonObject.optJSONObject("data").optString("count"));
|
if (page == 1) {
|
DiskLruCache.Editor editor = cache
|
.edit(getKey("getCouponRecommendGoods"));
|
editor.set(0, jsonObject.optJSONObject("data").optJSONArray("taoBaoCoupons").toString());
|
editor.commit();
|
}
|
requestState(mList.size() == 0 ? 1 : 0);
|
} else {
|
if (mList.size() == 0)
|
requestState(2);
|
}
|
}
|
|
@Override
|
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
|
super.onFailure(statusCode, headers, responseString, throwable);
|
Log.i("mResult", "请求错误--" + responseString);
|
if (cache != null) {
|
DiskLruCache.Snapshot snapshot = null;
|
try {
|
snapshot = cache.get(getKey("getCouponRecommendGoods"));
|
} catch (Exception e) {
|
|
}
|
if (snapshot == null && mList.size() == 0) {
|
if (NetUtils.getNetworkState(getContext()).equalsIgnoreCase(NetUtils.NETWORK_NONE)) {
|
requestState(3);
|
SingleToast.showToast(getContext(), "网络未连接,请检测网络设置");
|
} else {
|
requestState(2);
|
SingleToast.showToast(getContext(), "网络连接异常,请检测网络设置");
|
}
|
} else {
|
if (NetUtils.getNetworkState(getContext()).equalsIgnoreCase(NetUtils.NETWORK_NONE)) {
|
SingleToast.showToast(getContext(), "网络未连接,请检测网络设置");
|
} else {
|
SingleToast.showToast(getContext(), "网络连接异常,请检测网络设置");
|
}
|
}
|
} else {
|
if (NetUtils.getNetworkState(getContext()).equalsIgnoreCase(NetUtils.NETWORK_NONE)) {
|
requestState(3);
|
SingleToast.showToast(getContext(), "网络未连接,请检测网络设置");
|
} else {
|
requestState(2);
|
SingleToast.showToast(getContext(), "网络连接异常,请检测网络设置");
|
}
|
}
|
|
}
|
});
|
}
|
|
|
private String getKey(String method) {
|
return new Md5FileNameGenerator().generate(method);
|
}
|
|
@Override
|
public void onClick(View v) {
|
switch (v.getId()) {
|
case R.id.iv_slid_top:
|
lv_second_category.getLayoutManager().scrollToPosition(0);
|
break;
|
case R.id.tv_category_search:
|
if (StringUtils.isEmpty(et_search.getText().toString())) {
|
Toast.makeText(getContext(), "搜索内容不能为空!", Toast.LENGTH_LONG).show();
|
return;
|
}
|
String content = et_search.getText().toString();
|
content = content.trim();
|
Intent intent = new Intent(getContext(), SearchResultActivity.class);
|
intent.putExtra("content", content);
|
intent.putExtra("type", "coupon");
|
startActivity(intent);
|
break;
|
case R.id.iv_net_setting:
|
tv_loading.getContext().startActivity(new Intent(Settings.ACTION_SETTINGS));
|
break;
|
case R.id.tv_refresh:
|
// requestState(0);
|
// getGoodsList();
|
tv_loading.getContext().startActivity(new Intent(Settings.ACTION_SETTINGS));
|
break;
|
}
|
}
|
|
/**
|
* 请求状态 0 数据正常展示;1 返回数据为空;2 网络请求失败;3 没有连接网络
|
*
|
* @param state
|
*/
|
private void requestState(int state) {
|
srl_second_category.setVisibility(state == 0 ? View.VISIBLE : View.GONE);
|
lv_second_category.setVisibility(state == 0 ? View.VISIBLE : View.GONE);
|
ll_no_data.setVisibility(state == 1 ? View.VISIBLE : View.GONE);
|
ll_request_failture.setVisibility(state == 2 ? View.VISIBLE : View.GONE);
|
ll_no_net.setVisibility(state == 3 ? View.VISIBLE : View.GONE);
|
}
|
}
|