Repository: yxs666/cniao5-shop Branch: master Commit: bf109ed7b97b Files: 159 Total size: 414.8 KB Directory structure: gitextract_igovmuoh/ ├── CNiao5Shop.iml ├── README.md ├── app/ │ ├── .gitignore │ ├── app.iml │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── cniao5/ │ │ └── com/ │ │ └── cniao5shop/ │ │ └── ApplicationTest.java │ └── main/ │ ├── AndroidManifest.xml │ ├── assets/ │ │ └── ShareSDK.xml │ ├── java/ │ │ └── cniao5/ │ │ └── com/ │ │ └── cniao5shop/ │ │ ├── CniaoApplication.java │ │ ├── Contants.java │ │ ├── MainActivity.java │ │ ├── WareDetailActivity.java │ │ ├── WareListActivity.java │ │ ├── adapter/ │ │ │ ├── BaseAdapter.java │ │ │ ├── BaseViewHolder.java │ │ │ ├── CartAdapter.java │ │ │ ├── CategoryAdapter.java │ │ │ ├── HWAdatper.java │ │ │ ├── HomeCatgoryAdapter.java │ │ │ ├── HotWaresAdapter.java │ │ │ ├── SimpleAdapter.java │ │ │ ├── WaresAdapter.java │ │ │ └── decoration/ │ │ │ ├── CardViewtemDecortion.java │ │ │ ├── DividerGridItemDecoration.java │ │ │ └── DividerItemDecoration.java │ │ ├── bean/ │ │ │ ├── Banner.java │ │ │ ├── BaseBean.java │ │ │ ├── Campaign.java │ │ │ ├── Category.java │ │ │ ├── HomeCampaign.java │ │ │ ├── Page.java │ │ │ ├── ShoppingCart.java │ │ │ ├── Tab.java │ │ │ └── Wares.java │ │ ├── fragment/ │ │ │ ├── BaseFragment.java │ │ │ ├── CartFragment.java │ │ │ ├── CategoryFragment.java │ │ │ ├── HomeFragment.java │ │ │ ├── HotFragment.java │ │ │ └── MineFragment.java │ │ ├── http/ │ │ │ ├── BaseCallback.java │ │ │ ├── OkHttpHelper.java │ │ │ └── SpotsCallBack.java │ │ ├── utils/ │ │ │ ├── CartProvider.java │ │ │ ├── JSONUtil.java │ │ │ ├── Pager.java │ │ │ ├── PreferencesUtils.java │ │ │ ├── TimeUtils.java │ │ │ └── ToastUtils.java │ │ └── widget/ │ │ ├── CNiaoToolBar.java │ │ ├── FragmentTabHost.java │ │ └── NumberAddSubView.java │ └── res/ │ ├── color/ │ │ ├── grey_btn_text_color.xml │ │ ├── selector_tab_text.xml │ │ └── white_color_selector.xml │ ├── drawable/ │ │ ├── bg_btn_style_green.xml │ │ ├── bg_btn_style_grey.xml │ │ ├── bg_btn_style_red.xml │ │ ├── bg_btn_style_white.xml │ │ ├── selector_checkbox.xml │ │ ├── selector_icon_cart.xml │ │ ├── selector_icon_category.xml │ │ ├── selector_icon_home.xml │ │ ├── selector_icon_hot.xml │ │ ├── selector_icon_mine.xml │ │ ├── selector_list_item.xml │ │ ├── selector_number_add_sub.xml │ │ └── selector_search_view.xml │ ├── layout/ │ │ ├── activity_main.xml │ │ ├── activity_test.xml │ │ ├── activity_ware_detail.xml │ │ ├── activity_warelist.xml │ │ ├── fragment_cart.xml │ │ ├── fragment_category.xml │ │ ├── fragment_home.xml │ │ ├── fragment_hot.xml │ │ ├── fragment_mine.xml │ │ ├── tab_indicator.xml │ │ ├── template_cart.xml │ │ ├── template_grid_wares.xml │ │ ├── template_home_cardview.xml │ │ ├── template_home_cardview2.xml │ │ ├── template_hot_wares.xml │ │ ├── template_single_text.xml │ │ ├── toolbar.xml │ │ └── widet_num_add_sub.xml │ ├── menu/ │ │ └── menu_main.xml │ ├── values/ │ │ ├── attr_number_add_sub_view.xml │ │ ├── attrs.xml │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── ids.xml │ │ ├── strings.xml │ │ └── styles.xml │ ├── values-1280x768/ │ │ └── dimens.xml │ └── values-w820dp/ │ └── dimens.xml ├── build/ │ └── intermediates/ │ └── dex-cache/ │ └── cache.xml ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── local.properties ├── settings.gradle └── sharesdk/ ├── .gitignore ├── build.gradle ├── libs/ │ ├── MobCommons.jar │ ├── MobTools.jar │ ├── ShareSDK-Core-2.6.4.jar │ ├── ShareSDK-QQ-2.6.4.jar │ ├── ShareSDK-QZone-2.6.4.jar │ ├── ShareSDK-SinaWeibo-2.6.4.jar │ ├── ShareSDK-TencentWeibo-2.6.4.jar │ ├── ShareSDK-Wechat-2.6.4.jar │ ├── ShareSDK-Wechat-Core-2.6.4.jar │ ├── ShareSDK-Wechat-Favorite-2.6.4.jar │ └── ShareSDK-Wechat-Moments-2.6.4.jar ├── proguard-rules.pro ├── sharesdk.iml └── src/ ├── androidTest/ │ └── java/ │ └── cniao5/ │ └── com/ │ └── sharesdk/ │ └── ApplicationTest.java └── main/ ├── AndroidManifest.xml ├── java/ │ └── cn/ │ └── sharesdk/ │ └── onekeyshare/ │ ├── CustomerLogo.java │ ├── EditPageFakeActivity.java │ ├── FollowerListFakeActivity.java │ ├── OnekeyShare.java │ ├── OnekeyShareTheme.java │ ├── PicViewer.java │ ├── PlatformListFakeActivity.java │ ├── ReflectableShareContentCustomizeCallback.java │ ├── Shake2Share.java │ ├── ShareContentCustomizeCallback.java │ ├── ShareCore.java │ ├── ThemeShareCallback.java │ └── theme/ │ ├── classic/ │ │ ├── EditPage.java │ │ ├── FollowListPage.java │ │ ├── PlatformGridView.java │ │ └── PlatformListPage.java │ └── skyblue/ │ ├── EditPage.java │ ├── FollowListPage.java │ ├── PlatformGridViewAdapter.java │ └── PlatformListPage.java └── res/ ├── drawable/ │ ├── ssdk_oks_classic_platform_corners_bg.xml │ ├── ssdk_oks_skyblue_platform_list_item.xml │ ├── ssdk_oks_skyblue_platform_list_item_selected.xml │ └── ssdk_oks_skyblue_platform_list_selector.xml ├── drawable-xhdpi/ │ └── ssdk_oks_shake_to_share_back.xml ├── layout/ │ ├── ssdk_oks_skyblue_editpage.xml │ ├── ssdk_oks_skyblue_editpage_at_layout.xml │ ├── ssdk_oks_skyblue_editpage_inc_image_layout.xml │ ├── ssdk_oks_skyblue_share_actionbar.xml │ ├── ssdk_oks_skyblue_share_platform_list.xml │ └── ssdk_oks_skyblue_share_platform_list_item.xml ├── values/ │ ├── ssdk_instapaper_strings.xml │ ├── ssdk_oks_strings.xml │ └── ssdk_strings.xml └── values-en/ ├── ssdk_oks_strings.xml └── ssdk_strings.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: CNiao5Shop.iml ================================================ ================================================ FILE: README.md ================================================ **h2声明:**
此源码是菜鸟窝企业项目课程[《菜鸟商城》](http://www.cniao5.com/clazz/view/10073.html)的源码 我花了1000+大洋学习此课程获取到的,我分享源码出来未来大家方便学习,所以源码只限于学习用途,如用作商业用途与本人无关 **交流QQ群:** 374899552 **下载:**
课程地址:[《菜鸟商城》](http://www.cniao5.com/clazz/view/10073.html)
视频下载地址:http://pan.baidu.com/s/1dExm8lr 密码:c93f **【运行效果】**
================================================ FILE: app/.gitignore ================================================ /build ================================================ FILE: app/app.iml ================================================ ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "cniao5.com.cniao5shop" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.0.1' compile 'com.android.support:recyclerview-v7:23.0.1' compile 'com.jiechic.library:xUtils:2.6.14' compile 'com.nineoldandroids:library:2.4.0' compile 'com.daimajia.slider:library:1.1.5@aar' compile 'com.android.support:cardview-v7:23.0.1' compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.squareup.okhttp:okhttp:2.5.0' compile 'com.google.code.gson:gson:2.3.1' compile 'com.github.d-max:spots-dialog:0.4@aar' compile 'com.facebook.fresco:fresco:0.6.0+' compile 'com.facebook.fresco:imagepipeline-okhttp:0.6.0+' compile 'com.cjj.materialrefeshlayout:library:1.3.0' compile 'com.android.support:design:23.0.1' compile 'de.hdodenhof:circleimageview:2.0.0' compile project(':sharesdk') } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/Ivan/soft/dev/android/android-sdk-macosx/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: app/src/androidTest/java/cniao5/com/cniao5shop/ApplicationTest.java ================================================ package cniao5.com.cniao5shop; import android.app.Application; import android.test.ApplicationTestCase; /** * Testing Fundamentals */ public class ApplicationTest extends ApplicationTestCase { public ApplicationTest() { super(Application.class); } } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/assets/ShareSDK.xml ================================================ ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/CniaoApplication.java ================================================ package cniao5.com.cniao5shop; import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class CniaoApplication extends Application { @Override public void onCreate() { super.onCreate(); Fresco.initialize(this); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/Contants.java ================================================ package cniao5.com.cniao5shop; public class Contants { public static final String COMPAINGAIN_ID="compaigin_id"; public static final String WARE="ware"; public static class API{ public static final String BASE_URL="http://112.124.22.238:8081/course_api/"; public static final String CAMPAIGN_HOME=BASE_URL + "campaign/recommend"; public static final String BANNER=BASE_URL +"banner/query"; public static final String WARES_HOT=BASE_URL + "wares/hot"; public static final String WARES_LIST=BASE_URL +"wares/list"; public static final String WARES_CAMPAIN_LIST=BASE_URL +"wares/campaign/list"; public static final String WARES_DETAIL=BASE_URL +"wares/detail.html"; public static final String CATEGORY_LIST=BASE_URL +"category/list"; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/MainActivity.java ================================================ package cniao5.com.cniao5shop; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TabHost; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import cniao5.com.cniao5shop.bean.Tab; import cniao5.com.cniao5shop.fragment.CartFragment; import cniao5.com.cniao5shop.fragment.CategoryFragment; import cniao5.com.cniao5shop.fragment.HomeFragment; import cniao5.com.cniao5shop.fragment.HotFragment; import cniao5.com.cniao5shop.fragment.MineFragment; import cniao5.com.cniao5shop.widget.FragmentTabHost; public class MainActivity extends AppCompatActivity { private LayoutInflater mInflater; private FragmentTabHost mTabhost; private CartFragment cartFragment; private List mTabs = new ArrayList<>(5); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initTab(); } private void initTab() { Tab tab_home = new Tab(HomeFragment.class,R.string.home,R.drawable.selector_icon_home); Tab tab_hot = new Tab(HotFragment.class,R.string.hot,R.drawable.selector_icon_hot); Tab tab_category = new Tab(CategoryFragment.class,R.string.catagory,R.drawable.selector_icon_category); Tab tab_cart = new Tab(CartFragment.class,R.string.cart,R.drawable.selector_icon_cart); Tab tab_mine = new Tab(MineFragment.class,R.string.mine,R.drawable.selector_icon_mine); mTabs.add(tab_home); mTabs.add(tab_hot); mTabs.add(tab_category); mTabs.add(tab_cart); mTabs.add(tab_mine); mInflater = LayoutInflater.from(this); mTabhost = (FragmentTabHost) this.findViewById(android.R.id.tabhost); mTabhost.setup(this,getSupportFragmentManager(),R.id.realtabcontent); for (Tab tab : mTabs){ TabHost.TabSpec tabSpec = mTabhost.newTabSpec(getString(tab.getTitle())); tabSpec.setIndicator(buildIndicator(tab)); mTabhost.addTab(tabSpec,tab.getFragment(),null); } mTabhost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String tabId) { if(tabId==getString(R.string.cart)){ refData(); } } }); mTabhost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE); mTabhost.setCurrentTab(0); } private void refData(){ if(cartFragment == null){ Fragment fragment = getSupportFragmentManager().findFragmentByTag(getString(R.string.cart)); if(fragment !=null){ cartFragment= (CartFragment) fragment; cartFragment.refData(); } } else{ cartFragment.refData(); } } private View buildIndicator(Tab tab){ View view =mInflater.inflate(R.layout.tab_indicator,null); ImageView img = (ImageView) view.findViewById(R.id.icon_tab); TextView text = (TextView) view.findViewById(R.id.txt_indicator); img.setBackgroundResource(tab.getIcon()); text.setText(tab.getTitle()); return view; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/WareDetailActivity.java ================================================ package cniao5.com.cniao5shop; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import java.io.Serializable; import cn.sharesdk.framework.ShareSDK; import cn.sharesdk.onekeyshare.OnekeyShare; import cniao5.com.cniao5shop.bean.Wares; import cniao5.com.cniao5shop.utils.CartProvider; import cniao5.com.cniao5shop.utils.ToastUtils; import cniao5.com.cniao5shop.widget.CNiaoToolBar; import dmax.dialog.SpotsDialog; public class WareDetailActivity extends AppCompatActivity implements View.OnClickListener { @ViewInject(R.id.webView) private WebView mWebView; @ViewInject(R.id.toolbar) private CNiaoToolBar mToolBar; private Wares mWare; private WebAppInterface mAppInterfce; private CartProvider cartProvider; private SpotsDialog mDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ware_detail); ViewUtils.inject(this); Serializable serializable = getIntent().getSerializableExtra(Contants.WARE); if(serializable ==null) this.finish(); mDialog = new SpotsDialog(this,"loading...."); mDialog.show(); mWare = (Wares) serializable; cartProvider = new CartProvider(this); initToolBar(); initWebView(); } private void initWebView(){ WebSettings settings = mWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setBlockNetworkImage(false); settings.setAppCacheEnabled(true); mWebView.loadUrl(Contants.API.WARES_DETAIL); mAppInterfce = new WebAppInterface(this); mWebView.addJavascriptInterface(mAppInterfce,"appInterface"); mWebView.setWebViewClient(new WC()); } private void initToolBar(){ mToolBar.setNavigationOnClickListener(this); mToolBar.setRightButtonText("分享"); mToolBar.setRightButtonOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showShare(); } }); } private void showShare() { ShareSDK.initSDK(this); OnekeyShare oks = new OnekeyShare(); //关闭sso授权 oks.disableSSOWhenAuthorize(); // 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法 //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name)); // title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用 oks.setTitle(getString(R.string.share)); // titleUrl是标题的网络链接,仅在人人网和QQ空间使用 oks.setTitleUrl("http://www.cniao5.com"); // text是分享文本,所有平台都需要这个字段 oks.setText(mWare.getName()); // imagePath是图片的本地路径,Linked-In以外的平台都支持此参数 // oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片 oks.setImageUrl(mWare.getImgUrl()); // url仅在微信(包括好友和朋友圈)中使用 oks.setUrl("http://www.cniao5.com"); // comment是我对这条分享的评论,仅在人人网和QQ空间使用 oks.setComment(mWare.getName()); // site是分享此内容的网站名称,仅在QQ空间使用 oks.setSite(getString(R.string.app_name)); // siteUrl是分享此内容的网站地址,仅在QQ空间使用 oks.setSiteUrl("http://www.cniao5.com"); // 启动分享GUI oks.show(this); } @Override protected void onDestroy() { super.onDestroy(); ShareSDK.stopSDK(this); } @Override public void onClick(View v) { this.finish(); } class WC extends WebViewClient{ @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if(mDialog !=null && mDialog.isShowing()) mDialog.dismiss(); mAppInterfce.showDetail(); } } class WebAppInterface{ private Context mContext; public WebAppInterface(Context context){ mContext = context; } @JavascriptInterface public void showDetail(){ runOnUiThread(new Runnable() { @Override public void run() { mWebView.loadUrl("javascript:showDetail("+mWare.getId()+")"); } }); } @JavascriptInterface public void buy(long id){ cartProvider.put(mWare); ToastUtils.show(mContext,"已添加到购物车"); } @JavascriptInterface public void addFavorites(long id){ } } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/WareListActivity.java ================================================ package cniao5.com.cniao5shop; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.cjj.MaterialRefreshLayout; import com.google.gson.reflect.TypeToken; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import java.util.List; import cniao5.com.cniao5shop.adapter.BaseAdapter; import cniao5.com.cniao5shop.adapter.HWAdatper; import cniao5.com.cniao5shop.adapter.decoration.DividerItemDecoration; import cniao5.com.cniao5shop.bean.Page; import cniao5.com.cniao5shop.bean.Wares; import cniao5.com.cniao5shop.utils.Pager; import cniao5.com.cniao5shop.widget.CNiaoToolBar; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class WareListActivity extends AppCompatActivity implements Pager.OnPageListener,TabLayout.OnTabSelectedListener,View.OnClickListener { private static final String TAG = "WareListActivity"; public static final int TAG_DEFAULT=0; public static final int TAG_SALE=1; public static final int TAG_PRICE=2; public static final int ACTION_LIST=1; public static final int ACTION_GIRD=2; @ViewInject(R.id.tab_layout) private TabLayout mTablayout; @ViewInject(R.id.txt_summary) private TextView mTxtSummary; @ViewInject(R.id.recycler_view) private RecyclerView mRecyclerview_wares; @ViewInject(R.id.refresh_layout) private MaterialRefreshLayout mRefreshLayout; @ViewInject(R.id.toolbar) private CNiaoToolBar mToolbar; private int orderBy = 0; private long campaignId = 0; private HWAdatper mWaresAdapter; private Pager pager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_warelist); ViewUtils.inject(this); initToolBar(); campaignId=getIntent().getLongExtra(Contants.COMPAINGAIN_ID,0); initTab(); getData(); } private void initToolBar(){ mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WareListActivity.this.finish(); } }); mToolbar.setRightButtonIcon(R.drawable.icon_grid_32); mToolbar.getRightButton().setTag(ACTION_LIST); mToolbar.setRightButtonOnClickListener(this); } private void getData(){ pager= Pager.newBuilder().setUrl(Contants.API.WARES_CAMPAIN_LIST) .putParam("campaignId",campaignId) .putParam("orderBy",orderBy) .setRefreshLayout(mRefreshLayout) .setLoadMore(true) .setOnPageListener(this) .build(this,new TypeToken>(){}.getType()); pager.request(); } private void initTab(){ TabLayout.Tab tab= mTablayout.newTab(); tab.setText("默认"); tab.setTag(TAG_DEFAULT); mTablayout.addTab(tab); tab= mTablayout.newTab(); tab.setText("价格"); tab.setTag(TAG_PRICE); mTablayout.addTab(tab); tab= mTablayout.newTab(); tab.setText("销量"); tab.setTag(TAG_SALE); mTablayout.addTab(tab); mTablayout.setOnTabSelectedListener(this); } @Override public void load(List datas, int totalPage, int totalCount) { mTxtSummary.setText("共有"+totalCount+"件商品"); if (mWaresAdapter == null) { mWaresAdapter = new HWAdatper(this, datas); mWaresAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Wares wares = mWaresAdapter.getItem(position); Intent intent = new Intent(WareListActivity.this, WareDetailActivity.class); intent.putExtra(Contants.WARE,wares); startActivity(intent); } }); mRecyclerview_wares.setAdapter(mWaresAdapter); mRecyclerview_wares.setLayoutManager(new LinearLayoutManager(this)); mRecyclerview_wares.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST)); mRecyclerview_wares.setItemAnimator(new DefaultItemAnimator()); } else { mWaresAdapter.refreshData(datas); } } @Override public void refresh(List datas, int totalPage, int totalCount) { mWaresAdapter.refreshData(datas); mRecyclerview_wares.scrollToPosition(0); } @Override public void loadMore(List datas, int totalPage, int totalCount) { mWaresAdapter.loadMoreData(datas); } @Override public void onTabSelected(TabLayout.Tab tab) { orderBy = (int) tab.getTag(); pager.putParam("orderBy",orderBy); pager.request(); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } @Override public void onClick(View v) { int action = (int) v.getTag(); if(ACTION_LIST == action){ mToolbar.setRightButtonIcon(R.drawable.icon_list_32); mToolbar.getRightButton().setTag(ACTION_GIRD); mWaresAdapter.resetLayout(R.layout.template_grid_wares); mRecyclerview_wares.setLayoutManager(new GridLayoutManager(this,2)); } else if(ACTION_GIRD == action){ mToolbar.setRightButtonIcon(R.drawable.icon_grid_32); mToolbar.getRightButton().setTag(ACTION_LIST); mWaresAdapter.resetLayout(R.layout.template_hot_wares); mRecyclerview_wares.setLayoutManager(new LinearLayoutManager(this)); } } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/BaseAdapter.java ================================================ package cniao5.com.cniao5shop.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public abstract class BaseAdapter extends RecyclerView.Adapter{ protected static final String TAG = BaseAdapter.class.getSimpleName(); protected final Context context; protected int layoutResId; protected List datas; private OnItemClickListener mOnItemClickListener = null; public interface OnItemClickListener { void onItemClick(View view, int position); } public BaseAdapter(Context context, int layoutResId) { this(context, layoutResId, null); } public BaseAdapter(Context context, int layoutResId, List datas) { this.datas = datas == null ? new ArrayList() : datas; this.context = context; this.layoutResId = layoutResId; } @Override public BaseViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(layoutResId, viewGroup, false); BaseViewHolder vh = new BaseViewHolder(view,mOnItemClickListener); return vh; } @Override public void onBindViewHolder(BaseViewHolder viewHoder, int position) { T item = getItem(position); convert((H)viewHoder, item); } @Override public int getItemCount() { if(datas==null || datas.size()<=0) return 0; return datas.size(); } public T getItem(int position) { if (position >= datas.size()) return null; return datas.get(position); } public void clear(){ // int itemCount = datas.size(); // datas.clear(); // this.notifyItemRangeRemoved(0,itemCount); for (Iterator it=datas.iterator();it.hasNext();){ T t = (T) it.next(); int position = datas.indexOf(t); it.remove(); notifyItemRemoved(position); } } /** * 从列表中删除某项 * @param t */ public void removeItem(T t){ int position = datas.indexOf(t); datas.remove(position); notifyItemRemoved(position); } public List getDatas(){ return datas; } public void addData(List datas){ addData(0,datas); } public void addData(int position,List list){ if(list !=null && list.size()>0) { for (T t:list) { datas.add(position, t); notifyItemInserted(position); } } } public void refreshData(List list){ if(list !=null && list.size()>0){ clear(); int size = list.size(); for (int i=0;i list){ if(list !=null && list.size()>0){ int size = list.size(); int begin = datas.size(); for (int i=0;i菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class BaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private SparseArray views; private BaseAdapter.OnItemClickListener mOnItemClickListener ; public BaseViewHolder(View itemView,BaseAdapter.OnItemClickListener onItemClickListener){ super(itemView); itemView.setOnClickListener(this); this.mOnItemClickListener =onItemClickListener; this.views = new SparseArray(); } public TextView getTextView(int viewId) { return retrieveView(viewId); } public Button getButton(int viewId) { return retrieveView(viewId); } public ImageView getImageView(int viewId) { return retrieveView(viewId); } public View getView(int viewId) { return retrieveView(viewId); } protected T retrieveView(int viewId) { View view = views.get(viewId); if (view == null) { view = itemView.findViewById(viewId); views.put(viewId, view); } return (T) view; } @Override public void onClick(View v) { if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(v,getLayoutPosition()); } } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/CartAdapter.java ================================================ package cniao5.com.cniao5shop.adapter; import android.content.Context; import android.net.Uri; import android.text.Html; import android.view.View; import android.widget.CheckBox; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import java.util.Iterator; import java.util.List; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.bean.ShoppingCart; import cniao5.com.cniao5shop.utils.CartProvider; import cniao5.com.cniao5shop.widget.NumberAddSubView; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class CartAdapter extends SimpleAdapter implements BaseAdapter.OnItemClickListener { public static final String TAG="CartAdapter"; private CheckBox checkBox; private TextView textView; private CartProvider cartProvider; public CartAdapter(Context context, List datas, final CheckBox checkBox,TextView tv) { super(context, R.layout.template_cart, datas); setCheckBox(checkBox); setTextView(tv); cartProvider = new CartProvider(context); setOnItemClickListener(this); showTotalPrice(); } @Override protected void convert(BaseViewHolder viewHoder, final ShoppingCart item) { viewHoder.getTextView(R.id.text_title).setText(item.getName()); viewHoder.getTextView(R.id.text_price).setText("¥"+item.getPrice()); SimpleDraweeView draweeView = (SimpleDraweeView) viewHoder.getView(R.id.drawee_view); draweeView.setImageURI(Uri.parse(item.getImgUrl())); CheckBox checkBox = (CheckBox) viewHoder.getView(R.id.checkbox); checkBox.setChecked(item.isChecked()); NumberAddSubView numberAddSubView = (NumberAddSubView) viewHoder.getView(R.id.num_control); numberAddSubView.setValue(item.getCount()); numberAddSubView.setOnButtonClickListener(new NumberAddSubView.OnButtonClickListener() { @Override public void onButtonAddClick(View view, int value) { item.setCount(value); cartProvider.update(item); showTotalPrice(); } @Override public void onButtonSubClick(View view, int value) { item.setCount(value); cartProvider.update(item); showTotalPrice(); } }); } private float getTotalPrice(){ float sum=0; if(!isNull()) return sum; for (ShoppingCart cart: datas) { if(cart.isChecked()) sum += cart.getCount()*cart.getPrice(); } return sum; } public void showTotalPrice(){ float total = getTotalPrice(); textView.setText(Html.fromHtml("合计 ¥" + total + ""), TextView.BufferType.SPANNABLE); } private boolean isNull(){ return (datas !=null && datas.size()>0); } @Override public void onItemClick(View view, int position) { ShoppingCart cart = getItem(position); cart.setIsChecked(!cart.isChecked()); notifyItemChanged(position); checkListen(); showTotalPrice(); } private void checkListen() { int count = 0; int checkNum = 0; if (datas != null) { count = datas.size(); for (ShoppingCart cart : datas) { if (!cart.isChecked()) { checkBox.setChecked(false); break; } else { checkNum = checkNum + 1; } } if (count == checkNum) { checkBox.setChecked(true); } } } public void checkAll_None(boolean isChecked){ if(!isNull()) return ; int i=0; for (ShoppingCart cart :datas){ cart.setIsChecked(isChecked); notifyItemChanged(i); i++; } } public void delCart(){ if(!isNull()) return ; // for (ShoppingCart cart : datas){ // // if(cart.isChecked()){ // int position = datas.indexOf(cart); // cartProvider.delete(cart); // datas.remove(cart); // notifyItemRemoved(position); // } // } for(Iterator iterator = datas.iterator();iterator.hasNext();){ ShoppingCart cart = (ShoppingCart) iterator.next(); if(cart.isChecked()){ int position = datas.indexOf(cart); cartProvider.delete(cart); iterator.remove(); notifyItemRemoved(position); } } } public void setTextView(TextView textview){ this.textView = textview; } public void setCheckBox(CheckBox ck){ this.checkBox = ck; checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkAll_None(checkBox.isChecked()); showTotalPrice(); } }); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/CategoryAdapter.java ================================================ package cniao5.com.cniao5shop.adapter; import android.content.Context; import java.util.List; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.bean.Category; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class CategoryAdapter extends SimpleAdapter { public CategoryAdapter(Context context, List datas) { super(context, R.layout.template_single_text, datas); } @Override protected void convert(BaseViewHolder viewHoder, Category item) { viewHoder.getTextView(R.id.textView).setText(item.getName()); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/HWAdatper.java ================================================ package cniao5.com.cniao5shop.adapter; import android.content.Context; import android.net.Uri; import android.view.View; import android.widget.Button; import com.facebook.drawee.view.SimpleDraweeView; import java.util.List; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.bean.Wares; import cniao5.com.cniao5shop.utils.CartProvider; import cniao5.com.cniao5shop.utils.ToastUtils; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class HWAdatper extends SimpleAdapter { CartProvider provider ; public HWAdatper(Context context, List datas) { super(context, R.layout.template_hot_wares, datas); provider = new CartProvider(context); } @Override protected void convert(BaseViewHolder viewHolder, final Wares wares) { SimpleDraweeView draweeView = (SimpleDraweeView) viewHolder.getView(R.id.drawee_view); draweeView.setImageURI(Uri.parse(wares.getImgUrl())); viewHolder.getTextView(R.id.text_title).setText(wares.getName()); viewHolder.getTextView(R.id.text_price).setText("¥ "+wares.getPrice()); Button button =viewHolder.getButton(R.id.btn_add); if(button !=null) { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { provider.put(wares); ToastUtils.show(context, "已添加到购物车"); } }); } } public void resetLayout(int layoutId){ this.layoutResId = layoutId; notifyItemRangeChanged(0,getDatas().size()); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/HomeCatgoryAdapter.java ================================================ package cniao5.com.cniao5shop.adapter; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.List; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.bean.Campaign; import cniao5.com.cniao5shop.bean.HomeCampaign; /** * Created by Ivan on 15/9/30. */ public class HomeCatgoryAdapter extends RecyclerView.Adapter { private static int VIEW_TYPE_L=0; private static int VIEW_TYPE_R=1; private LayoutInflater mInflater; private List mDatas; private Context mContext; private OnCampaignClickListener mListener; public HomeCatgoryAdapter(List datas,Context context){ mDatas = datas; this.mContext = context; } public void setOnCampaignClickListener(OnCampaignClickListener listener){ this.mListener = listener; } @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) { mInflater = LayoutInflater.from(viewGroup.getContext()); if(type == VIEW_TYPE_R){ return new ViewHolder(mInflater.inflate(R.layout.template_home_cardview2,viewGroup,false)); } return new ViewHolder(mInflater.inflate(R.layout.template_home_cardview,viewGroup,false)); } @Override public void onBindViewHolder(ViewHolder viewHolder, int i) { HomeCampaign homeCampaign = mDatas.get(i); viewHolder.textTitle.setText(homeCampaign.getTitle()); Picasso.with(mContext).load(homeCampaign.getCpOne().getImgUrl()).into(viewHolder.imageViewBig); Picasso.with(mContext).load(homeCampaign.getCpTwo().getImgUrl()).into(viewHolder.imageViewSmallTop); Picasso.with(mContext).load(homeCampaign.getCpThree().getImgUrl()).into(viewHolder.imageViewSmallBottom); } @Override public int getItemCount() { return mDatas.size(); } @Override public int getItemViewType(int position) { if(position % 2==0){ return VIEW_TYPE_R; } else return VIEW_TYPE_L; } class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ TextView textTitle; ImageView imageViewBig; ImageView imageViewSmallTop; ImageView imageViewSmallBottom; public ViewHolder(View itemView) { super(itemView); textTitle = (TextView) itemView.findViewById(R.id.text_title); imageViewBig = (ImageView) itemView.findViewById(R.id.imgview_big); imageViewSmallTop = (ImageView) itemView.findViewById(R.id.imgview_small_top); imageViewSmallBottom = (ImageView) itemView.findViewById(R.id.imgview_small_bottom); imageViewBig.setOnClickListener(this); imageViewSmallTop.setOnClickListener(this); imageViewSmallBottom.setOnClickListener(this); } @Override public void onClick(View v) { if(mListener !=null){ anim(v); } } private void anim(final View v){ ObjectAnimator animator = ObjectAnimator.ofFloat(v, "rotationX", 0.0F, 360.0F) .setDuration(200); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { HomeCampaign campaign = mDatas.get(getLayoutPosition()); switch (v.getId()){ case R.id.imgview_big: mListener.onClick(v, campaign.getCpOne()); break; case R.id.imgview_small_top: mListener.onClick(v, campaign.getCpTwo()); break; case R.id.imgview_small_bottom: mListener.onClick(v,campaign.getCpThree()); break; } } }); animator.start(); } } public interface OnCampaignClickListener{ void onClick(View view,Campaign campaign); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/HotWaresAdapter.java ================================================ package cniao5.com.cniao5shop.adapter; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import java.util.List; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.bean.Wares; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class HotWaresAdapter extends RecyclerView.Adapter { private List mDatas; private LayoutInflater mInflater; public HotWaresAdapter(List wares){ mDatas = wares; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { mInflater = LayoutInflater.from(parent.getContext()); View view = mInflater.inflate(R.layout.template_hot_wares,null); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Wares wares = getData(position); holder.draweeView.setImageURI(Uri.parse(wares.getImgUrl())); holder.textTitle.setText(wares.getName()); holder.textPrice.setText("¥"+wares.getPrice()); } public Wares getData(int position){ return mDatas.get(position); } public List getDatas(){ return mDatas; } public void clearData(){ mDatas.clear(); notifyItemRangeRemoved(0,mDatas.size()); } public void addData(List datas){ addData(0,datas); } public void addData(int position,List datas){ if(datas !=null && datas.size()>0) { mDatas.addAll(datas); notifyItemRangeChanged(position, mDatas.size()); } } @Override public int getItemCount() { if(mDatas!=null && mDatas.size()>0) return mDatas.size(); return 0; } class ViewHolder extends RecyclerView.ViewHolder{ SimpleDraweeView draweeView; TextView textTitle; TextView textPrice; public ViewHolder(View itemView) { super(itemView); draweeView = (SimpleDraweeView) itemView.findViewById(R.id.drawee_view); textTitle= (TextView) itemView.findViewById(R.id.text_title); textPrice= (TextView) itemView.findViewById(R.id.text_price); } } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/SimpleAdapter.java ================================================ package cniao5.com.cniao5shop.adapter; import android.content.Context; import java.util.List; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public abstract class SimpleAdapter extends BaseAdapter { public SimpleAdapter(Context context, int layoutResId) { super(context, layoutResId); } public SimpleAdapter(Context context, int layoutResId, List datas) { super(context, layoutResId, datas); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/WaresAdapter.java ================================================ package cniao5.com.cniao5shop.adapter; import android.content.Context; import android.net.Uri; import com.facebook.drawee.view.SimpleDraweeView; import java.util.List; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.bean.Wares; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class WaresAdapter extends SimpleAdapter { public WaresAdapter(Context context, List datas) { super(context, R.layout.template_grid_wares, datas); } @Override protected void convert(BaseViewHolder viewHoder, Wares item) { viewHoder.getTextView(R.id.text_title).setText(item.getName()); viewHoder.getTextView(R.id.text_price).setText("¥"+item.getPrice()); SimpleDraweeView draweeView = (SimpleDraweeView) viewHoder.getView(R.id.drawee_view); draweeView.setImageURI(Uri.parse(item.getImgUrl())); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/decoration/CardViewtemDecortion.java ================================================ package cniao5.com.cniao5shop.adapter.decoration; import android.graphics.Canvas; import android.graphics.Rect; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; public class CardViewtemDecortion extends RecyclerView.ItemDecoration { @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDraw(c, parent, state); } @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDrawOver(c, parent, state); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int layoutOrientation = getOrientation(parent); if (layoutOrientation == LinearLayoutManager.VERTICAL) { outRect.top = 10; outRect.left=5; outRect.right=5; } else if(layoutOrientation == LinearLayoutManager.HORIZONTAL) { outRect.left = 5; } } private int getOrientation(RecyclerView parent) { if (parent.getLayoutManager() instanceof LinearLayoutManager) { LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager(); return layoutManager.getOrientation(); } else throw new IllegalStateException("DividerItemDecoration can only be used with a LinearLayoutManager."); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/decoration/DividerGridItemDecoration.java ================================================ package cniao5.com.cniao5shop.adapter.decoration; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.LayoutManager; import android.support.v7.widget.RecyclerView.State; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.View; /** * * @author zhy * */ public class DividerGridItemDecoration extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[] { android.R.attr.listDivider }; private Drawable mDivider; public DividerGridItemDecoration(Context context) { final TypedArray a = context.obtainStyledAttributes(ATTRS); mDivider = a.getDrawable(0); a.recycle(); } @Override public void onDraw(Canvas c, RecyclerView parent, State state) { drawHorizontal(c, parent); drawVertical(c, parent); } private int getSpanCount(RecyclerView parent) { // 列数 int spanCount = -1; LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { spanCount = ((GridLayoutManager) layoutManager).getSpanCount(); } else if (layoutManager instanceof StaggeredGridLayoutManager) { spanCount = ((StaggeredGridLayoutManager) layoutManager) .getSpanCount(); } return spanCount; } public void drawHorizontal(Canvas c, RecyclerView parent) { int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int left = child.getLeft() - params.leftMargin; final int right = child.getRight() + params.rightMargin + mDivider.getIntrinsicWidth(); final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } public void drawVertical(Canvas c, RecyclerView parent) { final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int top = child.getTop() - params.topMargin; final int bottom = child.getBottom() + params.bottomMargin; final int left = child.getRight() + params.rightMargin; final int right = left + mDivider.getIntrinsicWidth(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } private boolean isLastColum(RecyclerView parent, int pos, int spanCount, int childCount) { LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { if ((pos + 1) % spanCount == 0)// 如果是最后一列,则不需要绘制右边 { return true; } } else if (layoutManager instanceof StaggeredGridLayoutManager) { int orientation = ((StaggeredGridLayoutManager) layoutManager) .getOrientation(); if (orientation == StaggeredGridLayoutManager.VERTICAL) { if ((pos + 1) % spanCount == 0)// 如果是最后一列,则不需要绘制右边 { return true; } } else { childCount = childCount - childCount % spanCount; if (pos >= childCount)// 如果是最后一列,则不需要绘制右边 return true; } } return false; } private boolean isLastRaw(RecyclerView parent, int pos, int spanCount, int childCount) { LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { childCount = childCount - childCount % spanCount; if (pos >= childCount)// 如果是最后一行,则不需要绘制底部 return true; } else if (layoutManager instanceof StaggeredGridLayoutManager) { int orientation = ((StaggeredGridLayoutManager) layoutManager) .getOrientation(); // StaggeredGridLayoutManager 且纵向滚动 if (orientation == StaggeredGridLayoutManager.VERTICAL) { childCount = childCount - childCount % spanCount; // 如果是最后一行,则不需要绘制底部 if (pos >= childCount) return true; } else // StaggeredGridLayoutManager 且横向滚动 { // 如果是最后一行,则不需要绘制底部 if ((pos + 1) % spanCount == 0) { return true; } } } return false; } @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { int spanCount = getSpanCount(parent); int childCount = parent.getAdapter().getItemCount(); if (isLastRaw(parent, itemPosition, spanCount, childCount))// 如果是最后一行,则不需要绘制底部 { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); } else if (isLastColum(parent, itemPosition, spanCount, childCount))// 如果是最后一列,则不需要绘制右边 { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), mDivider.getIntrinsicHeight()); } } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/adapter/decoration/DividerItemDecoration.java ================================================ package cniao5.com.cniao5shop.adapter.decoration; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; public class DividerItemDecoration extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[]{ android.R.attr.listDivider }; public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; private Drawable mDivider; private int mOrientation; public DividerItemDecoration(Context context, int orientation) { final TypedArray a = context.obtainStyledAttributes(ATTRS); mDivider = a.getDrawable(0); a.recycle(); setOrientation(orientation); } public void setOrientation(int orientation) { if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { throw new IllegalArgumentException("invalid orientation"); } mOrientation = orientation; } @Override public void onDraw(Canvas c, RecyclerView parent) { // Log.v("recyclerview - itemdecoration", "onDraw()"); if (mOrientation == VERTICAL_LIST) { drawVertical(c, parent); } else { drawHorizontal(c, parent); } } public void drawVertical(Canvas c, RecyclerView parent) { final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext()); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } public void drawHorizontal(Canvas c, RecyclerView parent) { final int top = parent.getPaddingTop(); final int bottom = parent.getHeight() - parent.getPaddingBottom(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int left = child.getRight() + params.rightMargin; final int right = left + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { if (mOrientation == VERTICAL_LIST) { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); } } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/bean/Banner.java ================================================ package cniao5.com.cniao5shop.bean; /** * Created by Ivan on 15/10/2. */ public class Banner extends BaseBean { private String name; private String imgUrl; private String description; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/bean/BaseBean.java ================================================ package cniao5.com.cniao5shop.bean; import java.io.Serializable; /** * Created by Ivan on 15/9/24. */ public class BaseBean implements Serializable { protected long id; public long getId() { return id; } public void setId(long id) { this.id = id; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/bean/Campaign.java ================================================ /* *Campaign.java *Created on 2015/10/3 下午10:34 by Ivan *Copyright(c)2014 Guangzhou Onion Information Technology Co., Ltd. *http://www.cniao5.com */ package cniao5.com.cniao5shop.bean; import java.io.Serializable; public class Campaign implements Serializable { private Long id; private String title; private String imgUrl; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/bean/Category.java ================================================ package cniao5.com.cniao5shop.bean; public class Category extends BaseBean { public Category() { } public Category(String name) { this.name = name; } public Category(long id ,String name) { this.id = id; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/bean/HomeCampaign.java ================================================ /* *CampaignRecommendEx.java *Created on 2015/10/4 上午12:12 by Ivan *Copyright(c)2014 Guangzhou Onion Information Technology Co., Ltd. *http://www.cniao5.com */ package cniao5.com.cniao5shop.bean; import java.io.Serializable; /** * Copyright(c)2014 Guangzhou Onion Information Technology Co., Ltd. * http://www.cniao5.com */ public class HomeCampaign implements Serializable { private Long id; private String title; private Campaign cpOne; private Campaign cpTwo; private Campaign cpThree; public Campaign getCpOne() { return cpOne; } public void setCpOne(Campaign cpOne) { this.cpOne = cpOne; } public Campaign getCpTwo() { return cpTwo; } public void setCpTwo(Campaign cpTwo) { this.cpTwo = cpTwo; } public Campaign getCpThree() { return cpThree; } public void setCpThree(Campaign cpThree) { this.cpThree = cpThree; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/bean/Page.java ================================================ package cniao5.com.cniao5shop.bean; import java.util.List; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class Page { private int currentPage; private int pageSize; private int totalPage; private int totalCount; private List list; public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public List getList() { return list; } public void setList(List list) { this.list = list; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/bean/ShoppingCart.java ================================================ package cniao5.com.cniao5shop.bean; import java.io.Serializable; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class ShoppingCart extends Wares implements Serializable { private int count; private boolean isChecked=true; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public boolean isChecked() { return isChecked; } public void setIsChecked(boolean isChecked) { this.isChecked = isChecked; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/bean/Tab.java ================================================ package cniao5.com.cniao5shop.bean; /** * Created by Ivan on 15/9/25. */ public class Tab { private int title; private int icon; private Class fragment; public Tab(Class fragment,int title, int icon) { this.title = title; this.icon = icon; this.fragment = fragment; } public int getTitle() { return title; } public void setTitle(int title) { this.title = title; } public int getIcon() { return icon; } public void setIcon(int icon) { this.icon = icon; } public Class getFragment() { return fragment; } public void setFragment(Class fragment) { this.fragment = fragment; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/bean/Wares.java ================================================ package cniao5.com.cniao5shop.bean; import java.io.Serializable; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class Wares implements Serializable { private Long id; private String name; private String imgUrl; private String description; private Float price; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/fragment/BaseFragment.java ================================================ package cniao5.com.cniao5shop.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.widget.CNiaoToolBar; public abstract class BaseFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = createView(inflater,container,savedInstanceState); ViewUtils.inject(this, view); initToolBar(); init(); return view; } public void initToolBar(){ } public abstract View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState); public abstract void init(); } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/fragment/CartFragment.java ================================================ package cniao5.com.cniao5shop.fragment; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; import com.lidroid.xutils.view.annotation.ViewInject; import com.lidroid.xutils.view.annotation.event.OnClick; import java.util.List; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.adapter.CartAdapter; import cniao5.com.cniao5shop.adapter.decoration.DividerItemDecoration; import cniao5.com.cniao5shop.bean.ShoppingCart; import cniao5.com.cniao5shop.utils.CartProvider; import cniao5.com.cniao5shop.widget.CNiaoToolBar; public class CartFragment extends BaseFragment implements View.OnClickListener{ public static final int ACTION_EDIT=1; public static final int ACTION_CAMPLATE=2; @ViewInject(R.id.recycler_view) private RecyclerView mRecyclerView; @ViewInject(R.id.checkbox_all) private CheckBox mCheckBox; @ViewInject(R.id.txt_total) private TextView mTextTotal; @ViewInject(R.id.btn_order) private Button mBtnOrder; @ViewInject(R.id.btn_del) private Button mBtnDel; @ViewInject(R.id.toolbar) protected CNiaoToolBar mToolbar; private CartAdapter mAdapter; private CartProvider cartProvider; @Override public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_cart,container,false); } @Override public void init() { cartProvider = new CartProvider(getContext()); changeToolbar(); showData(); } @OnClick(R.id.btn_del) public void delCart(View view){ mAdapter.delCart(); } private void showData(){ List carts = cartProvider.getAll(); mAdapter = new CartAdapter(getContext(),carts,mCheckBox,mTextTotal); mRecyclerView.setAdapter(mAdapter); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL_LIST)); } public void refData(){ mAdapter.clear(); List carts = cartProvider.getAll(); mAdapter.addData(carts); mAdapter.showTotalPrice(); } public void changeToolbar(){ mToolbar.hideSearchView(); mToolbar.showTitleView(); mToolbar.setTitle(R.string.cart); mToolbar.getRightButton().setVisibility(View.VISIBLE); mToolbar.setRightButtonText("编辑"); mToolbar.getRightButton().setOnClickListener(this); mToolbar.getRightButton().setTag(ACTION_EDIT); } private void showDelControl(){ mToolbar.getRightButton().setText("完成"); mTextTotal.setVisibility(View.GONE); mBtnOrder.setVisibility(View.GONE); mBtnDel.setVisibility(View.VISIBLE); mToolbar.getRightButton().setTag(ACTION_CAMPLATE); mAdapter.checkAll_None(false); mCheckBox.setChecked(false); } private void hideDelControl(){ mTextTotal.setVisibility(View.VISIBLE); mBtnOrder.setVisibility(View.VISIBLE); mBtnDel.setVisibility(View.GONE); mToolbar.setRightButtonText("编辑"); mToolbar.getRightButton().setTag(ACTION_EDIT); mAdapter.checkAll_None(true); mAdapter.showTotalPrice(); mCheckBox.setChecked(true); } @Override public void onClick(View v) { int action = (int) v.getTag(); if(ACTION_EDIT == action){ showDelControl(); } else if(ACTION_CAMPLATE == action){ hideDelControl(); } } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/fragment/CategoryFragment.java ================================================ package cniao5.com.cniao5shop.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cjj.MaterialRefreshLayout; import com.cjj.MaterialRefreshListener; import com.daimajia.slider.library.Animations.DescriptionAnimation; import com.daimajia.slider.library.SliderLayout; import com.daimajia.slider.library.SliderTypes.BaseSliderView; import com.daimajia.slider.library.SliderTypes.DefaultSliderView; import com.lidroid.xutils.view.annotation.ViewInject; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.util.List; import cniao5.com.cniao5shop.Contants; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.WareDetailActivity; import cniao5.com.cniao5shop.adapter.BaseAdapter; import cniao5.com.cniao5shop.adapter.CategoryAdapter; import cniao5.com.cniao5shop.adapter.WaresAdapter; import cniao5.com.cniao5shop.adapter.decoration.DividerItemDecoration; import cniao5.com.cniao5shop.bean.Banner; import cniao5.com.cniao5shop.bean.Category; import cniao5.com.cniao5shop.bean.Page; import cniao5.com.cniao5shop.bean.Wares; import cniao5.com.cniao5shop.http.BaseCallback; import cniao5.com.cniao5shop.http.OkHttpHelper; import cniao5.com.cniao5shop.http.SpotsCallBack; public class CategoryFragment extends BaseFragment { @ViewInject(R.id.recyclerview_category) private RecyclerView mRecyclerView; @ViewInject(R.id.recyclerview_wares) private RecyclerView mRecyclerviewWares; @ViewInject(R.id.refresh_layout) private MaterialRefreshLayout mRefreshLaout; @ViewInject(R.id.slider) private SliderLayout mSliderLayout; private CategoryAdapter mCategoryAdapter; private WaresAdapter mWaresAdatper; private OkHttpHelper mHttpHelper = OkHttpHelper.getInstance(); private int currPage=1; private int totalPage=1; private int pageSize=10; private long category_id=0; private static final int STATE_NORMAL=0; private static final int STATE_REFREH=1; private static final int STATE_MORE=2; private int state=STATE_NORMAL; @Override public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_category,container,false); } @Override public void init() { requestCategoryData(); requestBannerData(); initRefreshLayout(); } private void initRefreshLayout(){ mRefreshLaout.setLoadMore(true); mRefreshLaout.setMaterialRefreshListener(new MaterialRefreshListener() { @Override public void onRefresh(MaterialRefreshLayout materialRefreshLayout) { refreshData(); } @Override public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) { if(currPage <=totalPage) loadMoreData(); else{ // Toast.makeText() mRefreshLaout.finishRefreshLoadMore(); } } }); } private void refreshData(){ currPage =1; state=STATE_REFREH; requestWares(category_id); } private void loadMoreData(){ currPage = ++currPage; state = STATE_MORE; requestWares(category_id); } private void requestCategoryData(){ mHttpHelper.get(Contants.API.CATEGORY_LIST, new SpotsCallBack>(getContext()) { @Override public void onSuccess(Response response, List categories) { showCategoryData(categories); if(categories !=null && categories.size()>0) category_id = categories.get(0).getId(); requestWares(category_id); } @Override public void onError(Response response, int code, Exception e) { } }); } private void showCategoryData(List categories){ mCategoryAdapter = new CategoryAdapter(getContext(),categories); mCategoryAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Category category = mCategoryAdapter.getItem(position); category_id = category.getId(); currPage=1; state=STATE_NORMAL; requestWares(category_id); } }); mRecyclerView.setAdapter(mCategoryAdapter); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL_LIST)); } private void requestBannerData( ) { String url = Contants.API.BANNER+"?type=1"; mHttpHelper.get(url, new SpotsCallBack>(getContext()){ @Override public void onSuccess(Response response, List banners) { showSliderViews(banners); } @Override public void onError(Response response, int code, Exception e) { } }); } private void showSliderViews(List banners){ if(banners !=null){ for (Banner banner : banners){ DefaultSliderView sliderView = new DefaultSliderView(this.getActivity()); sliderView.image(banner.getImgUrl()); sliderView.description(banner.getName()); sliderView.setScaleType(BaseSliderView.ScaleType.Fit); mSliderLayout.addSlider(sliderView); } } mSliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom); mSliderLayout.setCustomAnimation(new DescriptionAnimation()); mSliderLayout.setPresetTransformer(SliderLayout.Transformer.Default); mSliderLayout.setDuration(3000); } private void requestWares(long categoryId){ String url = Contants.API.WARES_LIST+"?categoryId="+categoryId+"&curPage="+currPage+"&pageSize="+pageSize; mHttpHelper.get(url, new BaseCallback>() { @Override public void onBeforeRequest(Request request) { } @Override public void onFailure(Request request, Exception e) { } @Override public void onResponse(Response response) { } @Override public void onSuccess(Response response, Page waresPage) { currPage = waresPage.getCurrentPage(); totalPage =waresPage.getTotalPage(); showWaresData(waresPage.getList()); } @Override public void onError(Response response, int code, Exception e) { } }); } private void showWaresData(List wares){ switch (state){ case STATE_NORMAL: if(mWaresAdatper ==null) { mWaresAdatper = new WaresAdapter(getContext(), wares); mWaresAdatper.setOnItemClickListener(new BaseAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Wares wares = mWaresAdatper.getItem(position); Intent intent = new Intent(getActivity(), WareDetailActivity.class); intent.putExtra(Contants.WARE,wares); startActivity(intent); } }); mRecyclerviewWares.setAdapter(mWaresAdatper); mRecyclerviewWares.setLayoutManager(new GridLayoutManager(getContext(), 2)); mRecyclerviewWares.setItemAnimator(new DefaultItemAnimator()); // mRecyclerviewWares.addItemDecoration(new DividerGridItemDecoration(getContext())); } else{ mWaresAdatper.clear(); mWaresAdatper.addData(wares); } break; case STATE_REFREH: mWaresAdatper.clear(); mWaresAdatper.addData(wares); mRecyclerviewWares.scrollToPosition(0); mRefreshLaout.finishRefresh(); break; case STATE_MORE: mWaresAdatper.addData(mWaresAdatper.getDatas().size(),wares); mRecyclerviewWares.scrollToPosition(mWaresAdatper.getDatas().size()); mRefreshLaout.finishRefreshLoadMore(); break; } } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/fragment/HomeFragment.java ================================================ package cniao5.com.cniao5shop.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.daimajia.slider.library.Animations.DescriptionAnimation; import com.daimajia.slider.library.SliderLayout; import com.daimajia.slider.library.SliderTypes.BaseSliderView; import com.daimajia.slider.library.SliderTypes.TextSliderView; import com.google.gson.Gson; import com.lidroid.xutils.view.annotation.ViewInject; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.util.List; import cniao5.com.cniao5shop.Contants; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.WareListActivity; import cniao5.com.cniao5shop.adapter.HomeCatgoryAdapter; import cniao5.com.cniao5shop.adapter.decoration.CardViewtemDecortion; import cniao5.com.cniao5shop.bean.Banner; import cniao5.com.cniao5shop.bean.Campaign; import cniao5.com.cniao5shop.bean.HomeCampaign; import cniao5.com.cniao5shop.http.BaseCallback; import cniao5.com.cniao5shop.http.OkHttpHelper; import cniao5.com.cniao5shop.http.SpotsCallBack; public class HomeFragment extends BaseFragment { @ViewInject(R.id.slider) private SliderLayout mSliderLayout; @ViewInject(R.id.recyclerview) private RecyclerView mRecyclerView; private HomeCatgoryAdapter mAdatper; private static final String TAG="HomeFragment"; private Gson mGson = new Gson(); private List mBanner; private OkHttpHelper httpHelper = OkHttpHelper.getInstance(); @Override public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_home,container,false); } @Override public void init() { requestImages(); initRecyclerView(); } private void requestImages(){ String url ="http://112.124.22.238:8081/course_api/banner/query?type=1"; httpHelper.get(url, new SpotsCallBack>(getContext()){ @Override public void onSuccess(Response response, List banners) { mBanner = banners; initSlider(); } @Override public void onError(Response response, int code, Exception e) { } }); } private void initRecyclerView() { httpHelper.get(Contants.API.CAMPAIGN_HOME, new BaseCallback>() { @Override public void onBeforeRequest(Request request) { } @Override public void onFailure(Request request, Exception e) { } @Override public void onResponse(Response response) { } @Override public void onSuccess(Response response, List homeCampaigns) { initData(homeCampaigns); } @Override public void onError(Response response, int code, Exception e) { } }); } private void initData(List homeCampaigns){ mAdatper = new HomeCatgoryAdapter(homeCampaigns,getActivity()); mAdatper.setOnCampaignClickListener(new HomeCatgoryAdapter.OnCampaignClickListener() { @Override public void onClick(View view, Campaign campaign) { Intent intent = new Intent(getActivity(), WareListActivity.class); intent.putExtra(Contants.COMPAINGAIN_ID,campaign.getId()); startActivity(intent); } }); mRecyclerView.setAdapter(mAdatper); mRecyclerView.addItemDecoration(new CardViewtemDecortion()); mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity())); } private void initSlider(){ if(mBanner !=null){ for (Banner banner : mBanner){ TextSliderView textSliderView = new TextSliderView(this.getActivity()); textSliderView.image(banner.getImgUrl()); textSliderView.description(banner.getName()); textSliderView.setScaleType(BaseSliderView.ScaleType.Fit); mSliderLayout.addSlider(textSliderView); } } mSliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom); mSliderLayout.setCustomAnimation(new DescriptionAnimation()); mSliderLayout.setPresetTransformer(SliderLayout.Transformer.RotateUp); mSliderLayout.setDuration(3000); } @Override public void onDestroy() { super.onDestroy(); mSliderLayout.stopAutoCycle(); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/fragment/HotFragment.java ================================================ package cniao5.com.cniao5shop.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cjj.MaterialRefreshLayout; import com.google.gson.reflect.TypeToken; import com.lidroid.xutils.view.annotation.ViewInject; import java.util.List; import cniao5.com.cniao5shop.Contants; import cniao5.com.cniao5shop.R; import cniao5.com.cniao5shop.WareDetailActivity; import cniao5.com.cniao5shop.adapter.BaseAdapter; import cniao5.com.cniao5shop.adapter.HWAdatper; import cniao5.com.cniao5shop.bean.Page; import cniao5.com.cniao5shop.bean.Wares; import cniao5.com.cniao5shop.utils.Pager; public class HotFragment extends BaseFragment implements Pager.OnPageListener { private HWAdatper mAdatper; @ViewInject(R.id.recyclerview) private RecyclerView mRecyclerView; @ViewInject(R.id.refresh_view) private MaterialRefreshLayout mRefreshLaout; @Override public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_hot,container,false); } @Override public void init() { Pager pager = Pager.newBuilder() .setUrl(Contants.API.WARES_HOT) .setLoadMore(true) .setOnPageListener(this) .setPageSize(20) .setRefreshLayout(mRefreshLaout) .build(getContext(), new TypeToken>() {}.getType()); pager.request(); } @Override public void load(List datas, int totalPage, int totalCount) { mAdatper = new HWAdatper(getContext(),datas); mAdatper.setOnItemClickListener(new BaseAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Wares wares = mAdatper.getItem(position); Intent intent = new Intent(getActivity(), WareDetailActivity.class); intent.putExtra(Contants.WARE,wares); startActivity(intent); } }); mRecyclerView.setAdapter(mAdatper); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); // mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL_LIST)); } @Override public void refresh(List datas, int totalPage, int totalCount) { mAdatper.refreshData(datas); mRecyclerView.scrollToPosition(0); } @Override public void loadMore(List datas, int totalPage, int totalCount) { mAdatper.loadMoreData(datas); mRecyclerView.scrollToPosition(mAdatper.getDatas().size()); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/fragment/MineFragment.java ================================================ package cniao5.com.cniao5shop.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import cniao5.com.cniao5shop.R; /** * Created by Ivan on 15/9/22. */ public class MineFragment extends BaseFragment{ @Override public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_mine,container,false); } @Override public void init() { } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/http/BaseCallback.java ================================================ package cniao5.com.cniao5shop.http; import com.google.gson.internal.$Gson$Types; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public abstract class BaseCallback { public Type mType; static Type getSuperclassTypeParameter(Class subclass) { Type superclass = subclass.getGenericSuperclass(); if (superclass instanceof Class) { throw new RuntimeException("Missing type parameter."); } ParameterizedType parameterized = (ParameterizedType) superclass; return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]); } public BaseCallback() { mType = getSuperclassTypeParameter(getClass()); } public abstract void onBeforeRequest(Request request); public abstract void onFailure(Request request, Exception e) ; /** *请求成功时调用此方法 * @param response */ public abstract void onResponse(Response response); /** * * 状态码大于200,小于300 时调用此方法 * @param response * @param t * @throws IOException */ public abstract void onSuccess(Response response,T t) ; /** * 状态码400,404,403,500等时调用此方法 * @param response * @param code * @param e */ public abstract void onError(Response response, int code,Exception e) ; } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/http/OkHttpHelper.java ================================================ package cniao5.com.cniao5shop.http; import android.os.Handler; import android.os.Looper; import android.util.Log; import com.google.gson.Gson; import com.squareup.okhttp.Callback; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; public class OkHttpHelper { public static final String TAG="OkHttpHelper"; private static OkHttpHelper mInstance; private OkHttpClient mHttpClient; private Gson mGson; private Handler mHandler; static { mInstance = new OkHttpHelper(); } private OkHttpHelper(){ mHttpClient = new OkHttpClient(); mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS); mHttpClient.setReadTimeout(10,TimeUnit.SECONDS); mHttpClient.setWriteTimeout(30,TimeUnit.SECONDS); mGson = new Gson(); mHandler = new Handler(Looper.getMainLooper()); }; public static OkHttpHelper getInstance(){ return mInstance; } public void get(String url,BaseCallback callback){ Request request = buildGetRequest(url); request(request,callback); } public void post(String url,Map param, BaseCallback callback){ Request request = buildPostRequest(url,param); request(request,callback); } public void request(final Request request,final BaseCallback callback){ callback.onBeforeRequest(request); mHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { callbackFailure(callback, request, e); } @Override public void onResponse(Response response) throws IOException { // callback.onResponse(response); callbackResponse(callback,response); if(response.isSuccessful()) { String resultStr = response.body().string(); Log.d(TAG, "result=" + resultStr); if (callback.mType == String.class){ callbackSuccess(callback,response,resultStr); } else { try { Object obj = mGson.fromJson(resultStr, callback.mType); callbackSuccess(callback,response,obj); } catch (com.google.gson.JsonParseException e){ // Json解析的错误 callback.onError(response,response.code(),e); } } } else { callbackError(callback,response,null); } } }); } private void callbackSuccess(final BaseCallback callback , final Response response, final Object obj ){ mHandler.post(new Runnable() { @Override public void run() { callback.onSuccess(response, obj); } }); } private void callbackError(final BaseCallback callback , final Response response, final Exception e ){ mHandler.post(new Runnable() { @Override public void run() { callback.onError(response,response.code(),e); } }); } private void callbackFailure(final BaseCallback callback , final Request request, final IOException e ){ mHandler.post(new Runnable() { @Override public void run() { callback.onFailure(request,e); } }); } private void callbackResponse(final BaseCallback callback , final Response response ){ mHandler.post(new Runnable() { @Override public void run() { callback.onResponse(response); } }); } private Request buildPostRequest(String url,Map params){ return buildRequest(url,HttpMethodType.POST,params); } private Request buildGetRequest(String url){ return buildRequest(url,HttpMethodType.GET,null); } private Request buildRequest(String url,HttpMethodType methodType,Map params){ Request.Builder builder = new Request.Builder() .url(url); if (methodType == HttpMethodType.POST){ RequestBody body = builderFormData(params); builder.post(body); } else if(methodType == HttpMethodType.GET){ builder.get(); } return builder.build(); } private RequestBody builderFormData(Map params){ FormEncodingBuilder builder = new FormEncodingBuilder(); if(params !=null){ for (Map.Entry entry :params.entrySet() ){ builder.add(entry.getKey(),entry.getValue()); } } return builder.build(); } enum HttpMethodType{ GET, POST, } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/http/SpotsCallBack.java ================================================ package cniao5.com.cniao5shop.http; import android.content.Context; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import dmax.dialog.SpotsDialog; public abstract class SpotsCallBack extends BaseCallback { private Context mContext; private SpotsDialog mDialog; public SpotsCallBack(Context context){ mContext = context; initSpotsDialog(); } private void initSpotsDialog(){ mDialog = new SpotsDialog(mContext,"拼命加载中..."); } public void showDialog(){ mDialog.show(); } public void dismissDialog(){ mDialog.dismiss(); } public void setLoadMessage(int resId){ mDialog.setMessage(mContext.getString(resId)); } @Override public void onFailure(Request request, Exception e) { dismissDialog(); } @Override public void onBeforeRequest(Request request) { showDialog(); } @Override public void onResponse(Response response) { dismissDialog(); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/utils/CartProvider.java ================================================ package cniao5.com.cniao5shop.utils; import android.content.Context; import android.util.SparseArray; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; import cniao5.com.cniao5shop.bean.ShoppingCart; import cniao5.com.cniao5shop.bean.Wares; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class CartProvider { public static final String CART_JSON="cart_json"; private SparseArray datas =null; private Context mContext; public CartProvider(Context context){ mContext = context; datas = new SparseArray<>(10); listToSparse(); } public void put(ShoppingCart cart){ ShoppingCart temp = datas.get(cart.getId().intValue()); if(temp !=null){ temp.setCount(temp.getCount()+1); } else{ temp = cart; temp.setCount(1); } datas.put(cart.getId().intValue(),temp); commit(); } public void put(Wares wares){ ShoppingCart cart = convertData(wares); put(cart); } public void update(ShoppingCart cart){ datas.put(cart.getId().intValue(),cart); commit(); } public void delete(ShoppingCart cart){ datas.delete(cart.getId().intValue()); commit(); } public List getAll(){ return getDataFromLocal(); } public void commit(){ List carts = sparseToList(); PreferencesUtils.putString(mContext,CART_JSON,JSONUtil.toJSON(carts)); } private List sparseToList(){ int size = datas.size(); List list = new ArrayList<>(size); for (int i=0;i carts = getDataFromLocal(); if(carts!=null && carts.size()>0){ for (ShoppingCart cart: carts) { datas.put(cart.getId().intValue(),cart); } } } public List getDataFromLocal(){ String json = PreferencesUtils.getString(mContext,CART_JSON); List carts =null; if(json !=null ){ carts = JSONUtil.fromJson(json,new TypeToken>(){}.getType()); } return carts; } public ShoppingCart convertData(Wares item){ ShoppingCart cart = new ShoppingCart(); cart.setId(item.getId()); cart.setDescription(item.getDescription()); cart.setImgUrl(item.getImgUrl()); cart.setName(item.getName()); cart.setPrice(item.getPrice()); return cart; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/utils/JSONUtil.java ================================================ /* *JSONUtil.java *Created on 2014-9-29 上午9:54 by Ivan *Copyright(c)2014 Guangzhou Onion Information Technology Co., Ltd. *http://www.cniao5.com */ package cniao5.com.cniao5shop.utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.lang.reflect.Type; /** * Created by Ivan on 14-9-29. * Copyright(c)2014 Guangzhou Onion Information Technology Co., Ltd. * http://www.cniao5.com */ public class JSONUtil { private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); public static Gson getGson(){ return gson; } public static T fromJson(String json,Class clz){ return gson.fromJson(json,clz); } public static T fromJson(String json,Type type){ return gson.fromJson(json,type); } public static String toJSON(Object object){ return gson.toJson(object); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/utils/Pager.java ================================================ package cniao5.com.cniao5shop.utils; import android.content.Context; import android.widget.Toast; import com.cjj.MaterialRefreshLayout; import com.cjj.MaterialRefreshListener; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import cniao5.com.cniao5shop.bean.Page; import cniao5.com.cniao5shop.http.OkHttpHelper; import cniao5.com.cniao5shop.http.SpotsCallBack; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class Pager { private static Builder builder; private OkHttpHelper httpHelper; private static final int STATE_NORMAL=0; private static final int STATE_REFREH=1; private static final int STATE_MORE=2; private int state=STATE_NORMAL; private Pager(){ httpHelper = OkHttpHelper.getInstance(); initRefreshLayout(); } public static Builder newBuilder(){ builder = new Builder(); return builder; } public void request(){ requestData(); } public void putParam(String key,Object value){ builder.params.put(key,value); } private void initRefreshLayout(){ builder.mRefreshLayout.setLoadMore(builder.canLoadMore); builder.mRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() { @Override public void onRefresh(MaterialRefreshLayout materialRefreshLayout) { builder.mRefreshLayout.setLoadMore(builder.canLoadMore); refresh(); } @Override public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) { if(builder.pageIndex void showData(List datas,int totalPage,int totalCount){ if(datas ==null|| datas.size()<=0){ Toast.makeText(builder.mContext,"加载不到数据",Toast.LENGTH_LONG).show(); return; } if(STATE_NORMAL==state){ if(builder.onPageListener !=null){ builder.onPageListener.load(datas,totalPage,totalCount); } } else if(STATE_REFREH==state) { builder.mRefreshLayout.finishRefresh(); if(builder.onPageListener !=null){ builder.onPageListener.refresh(datas,totalPage,totalCount); } } else if(STATE_MORE == state){ builder.mRefreshLayout.finishRefreshLoadMore(); if(builder.onPageListener !=null){ builder.onPageListener.loadMore(datas,totalPage,totalCount); } } } /** * 刷新数据 */ private void refresh(){ state=STATE_REFREH; builder.pageIndex =1; requestData(); } /** * 隐藏数据 */ private void loadMore(){ state=STATE_MORE; builder.pageIndex =++builder.pageIndex; requestData(); } /** * 构建URL * @return */ private String buildUrl(){ return builder.mUrl +"?"+buildUrlParams(); } private String buildUrlParams() { HashMap map = builder.params; map.put("curPage",builder.pageIndex); map.put("pageSize",builder.pageSize); StringBuffer sb = new StringBuffer(); for (Map.Entry entry : map.entrySet()) { sb.append(entry.getKey() + "=" + entry.getValue()); sb.append("&"); } String s = sb.toString(); if (s.endsWith("&")) { s = s.substring(0,s.length()-1); } return s; } /** * */ public static class Builder{ private Context mContext; private Type mType; private String mUrl; private MaterialRefreshLayout mRefreshLayout; private boolean canLoadMore; private int totalPage = 1; private int pageIndex = 1; private int pageSize = 10; private HashMap params = new HashMap<>(5); private OnPageListener onPageListener; public Builder setUrl(String url){ builder.mUrl = url; return builder; } public Builder setPageSize(int pageSize){ this.pageSize = pageSize; return builder; } public Builder putParam(String key,Object value){ params.put(key,value); return builder; } public Builder setLoadMore(boolean loadMore){ this.canLoadMore = loadMore; return builder; } public Builder setRefreshLayout(MaterialRefreshLayout refreshLayout){ this.mRefreshLayout = refreshLayout; return builder; } public Builder setOnPageListener(OnPageListener onPageListener) { this.onPageListener = onPageListener; return builder; } public Pager build(Context context, Type type){ this.mType = type; this.mContext =context; valid(); return new Pager(); } private void valid(){ if(this.mContext==null) throw new RuntimeException("content can't be null"); if(this.mUrl==null || "".equals(this.mUrl)) throw new RuntimeException("url can't be null"); if(this.mRefreshLayout==null) throw new RuntimeException("MaterialRefreshLayout can't be null"); } } class RequestCallBack extends SpotsCallBack>{ public RequestCallBack(Context context) { super(context); super.mType = builder.mType; } @Override public void onFailure(Request request, Exception e) { dismissDialog(); Toast.makeText(builder.mContext,"请求出错:"+e.getMessage(),Toast.LENGTH_LONG).show(); if(STATE_REFREH==state) { builder.mRefreshLayout.finishRefresh(); } else if(STATE_MORE == state){ builder.mRefreshLayout.finishRefreshLoadMore(); } } @Override public void onSuccess(Response response, Page page) { builder.pageIndex = page.getCurrentPage(); builder.pageSize = page.getPageSize(); builder.totalPage = page.getTotalPage(); showData(page.getList(),page.getTotalPage(),page.getTotalCount()); } @Override public void onError(Response response, int code, Exception e) { Toast.makeText(builder.mContext,"加载数据失败",Toast.LENGTH_LONG).show(); if(STATE_REFREH==state) { builder.mRefreshLayout.finishRefresh(); } else if(STATE_MORE == state){ builder.mRefreshLayout.finishRefreshLoadMore(); } } } public interface OnPageListener{ void load(List datas,int totalPage,int totalCount); void refresh(List datas,int totalPage,int totalCount); void loadMore(List datas,int totalPage,int totalCount); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/utils/PreferencesUtils.java ================================================ package cniao5.com.cniao5shop.utils; import android.content.Context; import android.content.SharedPreferences; /** * PreferencesUtils, easy to get or put data *
    * Preference Name *
  • you can change preference name by {@link #PREFERENCE_NAME}
  • *
*
    * Put Value *
  • put string {@link #putString(Context, String, String)}
  • *
  • put int {@link #putInt(Context, String, int)}
  • *
  • put long {@link #putLong(Context, String, long)}
  • *
  • put float {@link #putFloat(Context, String, float)}
  • *
  • put boolean {@link #putBoolean(Context, String, boolean)}
  • *
*
    * Get Value *
  • get string {@link #getString(Context, String)}, {@link #getString(Context, String, String)}
  • *
  • get int {@link #getInt(Context, String)}, {@link #getInt(Context, String, int)}
  • *
  • get long {@link #getLong(Context, String)}, {@link #getLong(Context, String, long)}
  • *
  • get float {@link #getFloat(Context, String)}, {@link #getFloat(Context, String, float)}
  • *
  • get boolean {@link #getBoolean(Context, String)}, {@link #getBoolean(Context, String, boolean)}
  • *
* */ public class PreferencesUtils { public static String PREFERENCE_NAME = "Cniao_Pref_Common"; /** * put string preferences * * @param context * @param key The name of the preference to modify * @param value The new value for the preference * @return True if the new values were successfully written to persistent storage. */ public static boolean putString(Context context, String key, String value) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(key, value); return editor.commit(); } /** * get string preferences * * @param context * @param key The name of the preference to retrieve * @return The preference value if it exists, or null. Throws ClassCastException if there is a preference with this * name that is not a string * @see #getString(Context, String, String) */ public static String getString(Context context, String key) { return getString(context, key, null); } /** * get string preferences * * @param context * @param key The name of the preference to retrieve * @param defaultValue Value to return if this preference does not exist * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with * this name that is not a string */ public static String getString(Context context, String key, String defaultValue) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return settings.getString(key, defaultValue); } /** * put int preferences * * @param context * @param key The name of the preference to modify * @param value The new value for the preference * @return True if the new values were successfully written to persistent storage. */ public static boolean putInt(Context context, String key, int value) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putInt(key, value); return editor.commit(); } /** * get int preferences * * @param context * @param key The name of the preference to retrieve * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this * name that is not a int * @see #getInt(Context, String, int) */ public static int getInt(Context context, String key) { return getInt(context, key, -1); } /** * get int preferences * * @param context * @param key The name of the preference to retrieve * @param defaultValue Value to return if this preference does not exist * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with * this name that is not a int */ public static int getInt(Context context, String key, int defaultValue) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return settings.getInt(key, defaultValue); } /** * put long preferences * * @param context * @param key The name of the preference to modify * @param value The new value for the preference * @return True if the new values were successfully written to persistent storage. */ public static boolean putLong(Context context, String key, long value) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putLong(key, value); return editor.commit(); } /** * get long preferences * * @param context * @param key The name of the preference to retrieve * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this * name that is not a long * @see #getLong(Context, String, long) */ public static long getLong(Context context, String key) { return getLong(context, key, -1); } /** * get long preferences * * @param context * @param key The name of the preference to retrieve * @param defaultValue Value to return if this preference does not exist * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with * this name that is not a long */ public static long getLong(Context context, String key, long defaultValue) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return settings.getLong(key, defaultValue); } /** * put float preferences * * @param context * @param key The name of the preference to modify * @param value The new value for the preference * @return True if the new values were successfully written to persistent storage. */ public static boolean putFloat(Context context, String key, float value) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putFloat(key, value); return editor.commit(); } /** * get float preferences * * @param context * @param key The name of the preference to retrieve * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this * name that is not a float * @see #getFloat(Context, String, float) */ public static float getFloat(Context context, String key) { return getFloat(context, key, -1); } /** * get float preferences * * @param context * @param key The name of the preference to retrieve * @param defaultValue Value to return if this preference does not exist * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with * this name that is not a float */ public static float getFloat(Context context, String key, float defaultValue) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return settings.getFloat(key, defaultValue); } /** * put boolean preferences * * @param context * @param key The name of the preference to modify * @param value The new value for the preference * @return True if the new values were successfully written to persistent storage. */ public static boolean putBoolean(Context context, String key, boolean value) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(key, value); return editor.commit(); } /** * get boolean preferences, default is false * * @param context * @param key The name of the preference to retrieve * @return The preference value if it exists, or false. Throws ClassCastException if there is a preference with this * name that is not a boolean * @see #getBoolean(Context, String, boolean) */ public static boolean getBoolean(Context context, String key) { return getBoolean(context, key, false); } /** * get boolean preferences * * @param context * @param key The name of the preference to retrieve * @param defaultValue Value to return if this preference does not exist * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with * this name that is not a boolean */ public static boolean getBoolean(Context context, String key, boolean defaultValue) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); return settings.getBoolean(key, defaultValue); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/utils/TimeUtils.java ================================================ package cniao5.com.cniao5shop.utils; import java.text.SimpleDateFormat; import java.util.Date; /** * TimeUtils * */ public class TimeUtils { public static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static final SimpleDateFormat DATE_FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd"); /** * long time to string * * @param timeInMillis * @param dateFormat * @return */ public static String getTime(long timeInMillis, SimpleDateFormat dateFormat) { return dateFormat.format(new Date(timeInMillis)); } /** * long time to string, format is {@link #DEFAULT_DATE_FORMAT} * * @param timeInMillis * @return */ public static String getTime(long timeInMillis) { return getTime(timeInMillis, DEFAULT_DATE_FORMAT); } /** * get current time in milliseconds * * @return */ public static long getCurrentTimeInLong() { return System.currentTimeMillis(); } /** * get current time in milliseconds, format is {@link #DEFAULT_DATE_FORMAT} * * @return */ public static String getCurrentTimeInString() { return getTime(getCurrentTimeInLong()); } /** * get current time in milliseconds * * @return */ public static String getCurrentTimeInString(SimpleDateFormat dateFormat) { return getTime(getCurrentTimeInLong(), dateFormat); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/utils/ToastUtils.java ================================================ package cniao5.com.cniao5shop.utils; import android.content.Context; import android.widget.Toast; /** * ToastUtils * * */ public class ToastUtils { public static void show(Context context, int resId) { show(context, context.getResources().getText(resId), Toast.LENGTH_LONG); } public static void show(Context context, int resId, int duration) { show(context, context.getResources().getText(resId), duration); } public static void show(Context context, CharSequence text) { show(context, text, Toast.LENGTH_LONG); } public static void show(Context context, CharSequence text, int duration) { Toast.makeText(context, text, duration).show(); } public static void show(Context context, int resId, Object... args) { show(context, String.format(context.getResources().getString(resId), args), Toast.LENGTH_LONG); } public static void show(Context context, String format, Object... args) { show(context, String.format(format, args), Toast.LENGTH_LONG); } public static void show(Context context, int resId, int duration, Object... args) { show(context, String.format(context.getResources().getString(resId), args), duration); } public static void show(Context context, String format, int duration, Object... args) { show(context, String.format(format, args), duration); } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/widget/CNiaoToolBar.java ================================================ package cniao5.com.cniao5shop.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v7.internal.widget.TintTypedArray; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import cniao5.com.cniao5shop.R; public class CNiaoToolBar extends Toolbar { private LayoutInflater mInflater; private View mView; private TextView mTextTitle; private EditText mSearchView; private Button mRightButton; public CNiaoToolBar(Context context) { this(context,null); } public CNiaoToolBar(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CNiaoToolBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); setContentInsetsRelative(10,10); if(attrs !=null) { final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs, R.styleable.CNiaoToolBar, defStyleAttr, 0); final Drawable rightIcon = a.getDrawable(R.styleable.CNiaoToolBar_rightButtonIcon); if (rightIcon != null) { //setNavigationIcon(navIcon); setRightButtonIcon(rightIcon); } boolean isShowSearchView = a.getBoolean(R.styleable.CNiaoToolBar_isShowSearchView,false); if(isShowSearchView){ showSearchView(); hideTitleView(); } CharSequence rightButtonText = a.getText(R.styleable.CNiaoToolBar_rightButtonText); if(rightButtonText !=null){ setRightButtonText(rightButtonText); } a.recycle(); } } private void initView() { if(mView == null) { mInflater = LayoutInflater.from(getContext()); mView = mInflater.inflate(R.layout.toolbar, null); mTextTitle = (TextView) mView.findViewById(R.id.toolbar_title); mSearchView = (EditText) mView.findViewById(R.id.toolbar_searchview); mRightButton = (Button) mView.findViewById(R.id.toolbar_rightButton); LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL); addView(mView, lp); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public void setRightButtonIcon(Drawable icon){ if(mRightButton !=null){ mRightButton.setBackground(icon); mRightButton.setVisibility(VISIBLE); } } public void setRightButtonIcon(int icon){ setRightButtonIcon(getResources().getDrawable(icon)); } public void setRightButtonOnClickListener(OnClickListener li){ mRightButton.setOnClickListener(li); } public void setRightButtonText(CharSequence text){ mRightButton.setText(text); mRightButton.setVisibility(VISIBLE); } public void setRightButtonText(int id){ setRightButtonText(getResources().getString(id)); } public Button getRightButton(){ return this.mRightButton; } @Override public void setTitle(int resId) { setTitle(getContext().getText(resId)); } @Override public void setTitle(CharSequence title) { initView(); if(mTextTitle !=null) { mTextTitle.setText(title); showTitleView(); } } public void showSearchView(){ if(mSearchView !=null) mSearchView.setVisibility(VISIBLE); } public void hideSearchView(){ if(mSearchView !=null) mSearchView.setVisibility(GONE); } public void showTitleView(){ if(mTextTitle !=null) mTextTitle.setVisibility(VISIBLE); } public void hideTitleView() { if (mTextTitle != null) mTextTitle.setVisibility(GONE); } // // private void ensureRightButtonView() { // if (mRightImageButton == null) { // mRightImageButton = new ImageButton(getContext(), null, // android.support.v7.appcompat.R.attr.toolbarNavigationButtonStyle); // final LayoutParams lp = generateDefaultLayoutParams(); // lp.gravity = GravityCompat.START | (Gravity.VERTICAL_GRAVITY_MASK); // mRightImageButton.setLayoutParams(lp); // } // } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/widget/FragmentTabHost.java ================================================ package cniao5.com.cniao5shop.widget; /** * Created by monkey * on 2014/9/24 * 功能描述:修改过的FragmentTabHost,保存fragment实例不销毁 */ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TabHost; import android.widget.TabWidget; /** * Special TabHost that allows the use of {@link Fragment} objects for its tab * content. When placing this in a view hierarchy, after inflating the hierarchy * you must call {@link #setup(Context, FragmentManager, int)} to complete the * initialization of the tab host. * *

* Here is a simple example of using a FragmentTabHost in an Activity: * * {@sample * development/samples/Support4Demos/src/com/example/android/supportv4/app/ * FragmentTabs.java complete} * *

* This can also be used inside of a fragment through fragment nesting: * * {@sample * development/samples/Support4Demos/src/com/example/android/supportv4/app/ * FragmentTabsFragmentSupport.java complete} */ public class FragmentTabHost extends TabHost implements TabHost.OnTabChangeListener { private final ArrayList mTabs = new ArrayList(); private FrameLayout mRealTabContent; private Context mContext; private FragmentManager mFragmentManager; private int mContainerId; private OnTabChangeListener mOnTabChangeListener; private TabInfo mLastTab; private boolean mAttached; static final class TabInfo { private final String tag; private final Class clss; private final Bundle args; private Fragment fragment; TabInfo(String _tag, Class _class, Bundle _args) { tag = _tag; clss = _class; args = _args; } } static class DummyTabFactory implements TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } static class SavedState extends BaseSavedState { String curTab; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); curTab = in.readString(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeString(curTab); } @Override public String toString() { return "FragmentTabHost.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " curTab=" + curTab + "}"; } public static final Creator CREATOR = new Creator() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } public FragmentTabHost(Context context) { // Note that we call through to the version that takes an AttributeSet, // because the simple Context construct can result in a broken object! super(context, null); initFragmentTabHost(context, null); } public FragmentTabHost(Context context, AttributeSet attrs) { super(context, attrs); initFragmentTabHost(context, attrs); } private void initFragmentTabHost(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, new int[] { android.R.attr.inflatedId }, 0, 0); mContainerId = a.getResourceId(0, 0); a.recycle(); super.setOnTabChangedListener(this); } private void ensureHierarchy(Context context) { // If owner hasn't made its own view hierarchy, then as a convenience // we will construct a standard one here. if (findViewById(android.R.id.tabs) == null) { LinearLayout ll = new LinearLayout(context); ll.setOrientation(LinearLayout.VERTICAL); addView(ll, new LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); TabWidget tw = new TabWidget(context); tw.setId(android.R.id.tabs); tw.setOrientation(TabWidget.HORIZONTAL); ll.addView(tw, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0)); FrameLayout fl = new FrameLayout(context); fl.setId(android.R.id.tabcontent); ll.addView(fl, new LinearLayout.LayoutParams(0, 0, 0)); mRealTabContent = fl = new FrameLayout(context); mRealTabContent.setId(mContainerId); ll.addView(fl, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0, 1)); } } /** * @deprecated Don't call the original TabHost setup, you must instead call * {@link #setup(Context, FragmentManager)} or * {@link #setup(Context, FragmentManager, int)}. */ @Override @Deprecated public void setup() { throw new IllegalStateException( "Must call setup() that takes a Context and FragmentManager"); } public void setup(Context context, FragmentManager manager) { ensureHierarchy(context); // Ensure views required by super.setup() super.setup(); mContext = context; mFragmentManager = manager; ensureContent(); } public void setup(Context context, FragmentManager manager, int containerId) { ensureHierarchy(context); // Ensure views required by super.setup() super.setup(); mContext = context; mFragmentManager = manager; mContainerId = containerId; ensureContent(); mRealTabContent.setId(containerId); // We must have an ID to be able to save/restore our state. If // the owner hasn't set one at this point, we will set it ourself. if (getId() == View.NO_ID) { setId(android.R.id.tabhost); } } private void ensureContent() { if (mRealTabContent == null) { mRealTabContent = (FrameLayout) findViewById(mContainerId); if (mRealTabContent == null) { throw new IllegalStateException( "No tab content FrameLayout found for id " + mContainerId); } } } @Override public void setOnTabChangedListener(OnTabChangeListener l) { mOnTabChangeListener = l; } public void addTab(TabSpec tabSpec, Class clss, Bundle args) { tabSpec.setContent(new DummyTabFactory(mContext)); String tag = tabSpec.getTag(); TabInfo info = new TabInfo(tag, clss, args); if (mAttached) { // If we are already attached to the window, then check to make // sure this tab's fragment is inactive if it exists. This shouldn't // normally happen. info.fragment = mFragmentManager.findFragmentByTag(tag); if (info.fragment != null && !info.fragment.isDetached()) { FragmentTransaction ft = mFragmentManager.beginTransaction(); // ft.detach(info.fragment); ft.hide(info.fragment); ft.commit(); } } mTabs.add(info); addTab(tabSpec); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); String currentTab = getCurrentTabTag(); // Go through all tabs and make sure their fragments match // the correct state. FragmentTransaction ft = null; for (int i = 0; i < mTabs.size(); i++) { TabInfo tab = mTabs.get(i); tab.fragment = mFragmentManager.findFragmentByTag(tab.tag); // if (tab.fragment != null && !tab.fragment.isDetached()) { if (tab.fragment != null) { if (tab.tag.equals(currentTab)) { // The fragment for this tab is already there and // active, and it is what we really want to have // as the current tab. Nothing to do. mLastTab = tab; } else { // This fragment was restored in the active state, // but is not the current tab. Deactivate it. if (ft == null) { ft = mFragmentManager.beginTransaction(); } // ft.detach(tab.fragment); ft.hide(tab.fragment); } } } // We are now ready to go. Make sure we are switched to the // correct tab. mAttached = true; ft = doTabChanged(currentTab, ft); if (ft != null) { ft.commitAllowingStateLoss(); mFragmentManager.executePendingTransactions(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mAttached = false; } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.curTab = getCurrentTabTag(); return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); setCurrentTabByTag(ss.curTab); } @Override public void onTabChanged(String tabId) { if (mAttached) { FragmentTransaction ft = doTabChanged(tabId, null); if (ft != null) { ft.commit(); } } if (mOnTabChangeListener != null) { mOnTabChangeListener.onTabChanged(tabId); } } private FragmentTransaction doTabChanged(String tabId, FragmentTransaction ft) { TabInfo newTab = null; for (int i = 0; i < mTabs.size(); i++) { TabInfo tab = mTabs.get(i); if (tab.tag.equals(tabId)) { newTab = tab; } } if (newTab == null) { throw new IllegalStateException("No tab known for tag " + tabId); } if (mLastTab != newTab) { if (ft == null) { ft = mFragmentManager.beginTransaction(); } if (mLastTab != null) { if (mLastTab.fragment != null) { // ft.detach(mLastTab.fragment); ft.hide(mLastTab.fragment); } } if (newTab != null) { if (newTab.fragment == null) { newTab.fragment = Fragment.instantiate(mContext, newTab.clss.getName(), newTab.args); ft.add(mContainerId, newTab.fragment, newTab.tag); } else { // ft.attach(newTab.fragment); ft.show(newTab.fragment); } } mLastTab = newTab; } return ft; } } ================================================ FILE: app/src/main/java/cniao5/com/cniao5shop/widget/NumberAddSubView.java ================================================ package cniao5.com.cniao5shop.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v7.internal.widget.TintTypedArray; import android.text.InputType; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import cniao5.com.cniao5shop.R; /** * Created by 菜鸟窝 * 一个专业的Android开发在线教育平台 */ public class NumberAddSubView extends LinearLayout implements View.OnClickListener { public static final String TAG="NumberAddSubView"; public static final int DEFUALT_MAX=1000; private TextView mEtxtNum; private Button mBtnAdd; private Button mBtnSub; private OnButtonClickListener onButtonClickListener; private LayoutInflater mInflater; private int value; private int minValue; private int maxValue=DEFUALT_MAX; public NumberAddSubView(Context context) { this(context, null); } public NumberAddSubView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public NumberAddSubView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mInflater = LayoutInflater.from(context); initView(); if(attrs !=null){ final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs, R.styleable.NumberAddSubView, defStyleAttr, 0); int val = a.getInt(R.styleable.NumberAddSubView_value,0); setValue(val); int maxVal = a.getInt(R.styleable.NumberAddSubView_maxValue,0); if(maxVal!=0) setMaxValue(maxVal); int minVal = a.getInt(R.styleable.NumberAddSubView_minValue,0); setMinValue(minVal); Drawable etBackground = a.getDrawable(R.styleable.NumberAddSubView_editBackground); if(etBackground!=null) setEditTextBackground(etBackground); Drawable buttonAddBackground = a.getDrawable(R.styleable.NumberAddSubView_buttonAddBackgroud); if(buttonAddBackground!=null) setButtonAddBackgroud(buttonAddBackground); Drawable buttonSubBackground = a.getDrawable(R.styleable.NumberAddSubView_buttonSubBackgroud); if(buttonSubBackground!=null) setButtonSubBackgroud(buttonSubBackground); a.recycle(); } } private void initView(){ View view = mInflater.inflate(R.layout.widet_num_add_sub,this,true); mEtxtNum = (TextView) view.findViewById(R.id.etxt_num); mEtxtNum.setInputType(InputType.TYPE_NULL); mEtxtNum.setKeyListener(null); mBtnAdd = (Button) view.findViewById(R.id.btn_add); mBtnSub = (Button) view.findViewById(R.id.btn_sub); mBtnAdd.setOnClickListener(this); mBtnSub.setOnClickListener(this); } @Override public void onClick(View v) { if(v.getId() == R.id.btn_add){ numAdd(); if(onButtonClickListener !=null){ onButtonClickListener.onButtonAddClick(v,this.value); } } else if(v.getId()==R.id.btn_sub){ numSub(); if(onButtonClickListener !=null){ onButtonClickListener.onButtonSubClick(v,this.value); } } } private void numAdd(){ getValue(); if(this.value<=maxValue) this.value=+this.value+1; mEtxtNum.setText(value+""); } private void numSub(){ getValue(); if(this.value>minValue) this.value=this.value-1; mEtxtNum.setText(value+""); } public int getValue(){ String value = mEtxtNum.getText().toString(); if(value !=null && !"".equals(value)) this.value = Integer.parseInt(value); return this.value; } public void setValue(int value) { mEtxtNum.setText(value+""); this.value = value; } public void setMaxValue(int maxValue) { this.maxValue = maxValue; } public void setMinValue(int minValue) { this.minValue = minValue; } public void setEditTextBackground(Drawable drawable){ mEtxtNum.setBackgroundDrawable(drawable); } public void setEditTextBackground(int drawableId){ setEditTextBackground(getResources().getDrawable(drawableId)); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public void setButtonAddBackgroud(Drawable backgroud){ this.mBtnAdd.setBackground(backgroud); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public void setButtonSubBackgroud(Drawable backgroud){ this.mBtnSub.setBackground(backgroud); } public void setOnButtonClickListener(OnButtonClickListener onButtonClickListener) { this.onButtonClickListener = onButtonClickListener; } public interface OnButtonClickListener{ public void onButtonAddClick(View view, int value); public void onButtonSubClick(View view, int value); } } ================================================ FILE: app/src/main/res/color/grey_btn_text_color.xml ================================================ ================================================ FILE: app/src/main/res/color/selector_tab_text.xml ================================================ ================================================ FILE: app/src/main/res/color/white_color_selector.xml ================================================ ================================================ FILE: app/src/main/res/drawable/bg_btn_style_green.xml ================================================ ================================================ FILE: app/src/main/res/drawable/bg_btn_style_grey.xml ================================================ ================================================ FILE: app/src/main/res/drawable/bg_btn_style_red.xml ================================================ ================================================ FILE: app/src/main/res/drawable/bg_btn_style_white.xml ================================================ ================================================ FILE: app/src/main/res/drawable/selector_checkbox.xml ================================================ ================================================ FILE: app/src/main/res/drawable/selector_icon_cart.xml ================================================ ================================================ FILE: app/src/main/res/drawable/selector_icon_category.xml ================================================ ================================================ FILE: app/src/main/res/drawable/selector_icon_home.xml ================================================ ================================================ FILE: app/src/main/res/drawable/selector_icon_hot.xml ================================================ ================================================ FILE: app/src/main/res/drawable/selector_icon_mine.xml ================================================ ================================================ FILE: app/src/main/res/drawable/selector_list_item.xml ================================================ ================================================ FILE: app/src/main/res/drawable/selector_number_add_sub.xml ================================================ ================================================ FILE: app/src/main/res/drawable/selector_search_view.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_test.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_ware_detail.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_warelist.xml ================================================ ================================================ FILE: app/src/main/res/layout/fragment_cart.xml ================================================