main_activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.example.week03_month.MainActivity">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/rel_navigate"
android:layout_alignParentBottom="true">
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="首页"
android:button="@null"
android:gravity="center"
android:id="@+id/rb_index"
android:padding="3dp"
android:background="@drawable/rb_selector"
android:checked="true"/>
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="发现"
android:button="@null"
android:padding="3dp"
android:gravity="center"
android:id="@+id/rb_discovery"
android:background="@drawable/rb_selector"/>
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="下载"
android:button="@null"
android:gravity="center"
android:padding="3dp"
android:id="@+id/rb_down"
android:background="@drawable/rb_selector"/>
<RadioButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="我的"
android:padding="3dp"
android:button="@null"
android:gravity="center"
android:id="@+id/rb_me"
android:background="@drawable/rb_selector"/>
</RadioGroup>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/rel_navigate"
android:id="@+id/main_content"></FrameLayout>
</RelativeLayout>
shouye_fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="40dp"
app:tabGravity="center"
app:tabIndicatorColor="@color/colorAccent"
app:tabMode="scrollable"
android:id="@+id/myTab"
></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/vp"
></android.support.v4.view.ViewPager>
</LinearLayout>
tablayout_fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ptr="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.handmark.pulltorefresh.library.PullToRefreshScrollView
android:id="@+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
ptr:ptrAnimationStyle="flip"
ptr:ptrDrawable="@drawable/default_ptr_flip"
ptr:ptrHeaderBackground="#383838"
ptr:ptrHeaderTextColor="#FFFFFF">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.youth.banner.Banner
android:id="@+id/Banner"
android:layout_width="match_parent"
android:layout_height="200dp"></com.youth.banner.Banner>
<com.example.week03_month.MyListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent"></com.example.week03_month.MyListView>
</LinearLayout>
</com.handmark.pulltorefresh.library.PullToRefreshScrollView>
</LinearLayout>
item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/img"
android:layout_width="130dp"
android:layout_height="130dp" />
<TextView
android:id="@+id/tv_title"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
rb_selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:drawable="@android:color/holo_red_dark"></item>
</selector>
fragment
ShouyeFragment
package com.example.week03_month.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.week03_month.R;
import com.example.week03_month.adapter.MyPagerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ass on 2017/10/24.
*/
public class ShouyeFragment extends Fragment {
private View view;
private TabLayout myTab;
private ViewPager viewPager;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view=View.inflate(getActivity(), R.layout.shouye_fragment,null);
myTab = (TabLayout) view.findViewById(R.id.myTab);
viewPager = (ViewPager) view.findViewById(R.id.vp);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//初使化标题
List<String> titles=new ArrayList<>();
titles.add("推荐");
titles.add("课程");
titles.add("实战");
titles.add("职业路径");
//设置适配器-注意:传递的fragmentManager是 getChild...... 不是 getSupport...
viewPager.setAdapter(new MyPagerAdapter(getChildFragmentManager(),titles));
//设置一次加载所有页面
viewPager.setOffscreenPageLimit(titles.size());
//将tabLayout与viewpager建立关联
myTab.setupWithViewPager(viewPager);
}
}
ContentFragment
package com.example.week03_month.fragment;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ScrollView;
import com.example.week03_month.R;
import com.example.week03_month.Result;
import com.example.week03_month.Utils.MyBanner;
import com.example.week03_month.Utils.MyTask;
import com.example.week03_month.adapter.MyAdapter;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.youth.banner.Banner;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ass on 2017/10/24.
*/
public class ContentFragment extends Fragment {
private Banner myBanner;
private PullToRefreshScrollView scrollView;
private ListView listView;
//列表显示的数据
private List<Result.DataEntity> datas=new ArrayList<>();
private MyAdapter myAdapter;
//页数
private int startNum=0;
private View view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view=View.inflate(getActivity(), R.layout.recommend_layout,null);
myBanner= (Banner) view.findViewById(R.id.Banner);
scrollView = (PullToRefreshScrollView) view.findViewById(R.id.scroll_view);
listView = (ListView) view.findViewById(R.id.lv);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initRefreshScrollView();
//请求数据
addToTop();
}
public void initRefreshScrollView(){
//设置模式
scrollView.setMode(PullToRefreshBase.Mode.BOTH);
//设置头尾布局显示的文本
ILoadingLayout headerLables=scrollView.getLoadingLayoutProxy(true,false);
headerLables.setPullLabel("下拉刷新");
headerLables.setRefreshingLabel("正在刷新");
headerLables.setReleaseLabel("松开刷新");
ILoadingLayout footerLables=scrollView.getLoadingLayoutProxy(false,true);
footerLables.setPullLabel("上拉加载");
footerLables.setRefreshingLabel("正在加载");
footerLables.setReleaseLabel("松开加载");
//设置监听事件
scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
//下拉刷新
addToTop();
closeRefresh();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
//上拉加载更多
addToBottom();
closeRefresh();
}
});
}
public void addToBottom(){
startNum=startNum+20;
//请求数据
MyTask myTask=new MyTask(new MyTask.Icallbacks() {
@Override
public void updateUiByjson(String jsonstr) {
Gson gson=new Gson();
Result result=gson.fromJson(jsonstr, Result.class);
//得到列表显示的数据
datas.addAll(result.getData());
//设置适配器
setAdapter();
//设置轮播图
setBanner(result.getDataScroll());
}
});
myTask.execute("http://www.93.gov.cn/93app/data.do?channelId=0&startNum="+startNum);
}
public void addToTop(){
//请求数据
MyTask myTask=new MyTask(new MyTask.Icallbacks() {
@Override
public void updateUiByjson(String jsonstr) {
Gson gson=new Gson();
Result result=gson.fromJson(jsonstr, Result.class);
//清空
datas.clear();
//得到列表显示的数据
datas.addAll(result.getData());
//设置适配器
setAdapter();
//设置轮播图
setBanner(result.getDataScroll());
}
});
myTask.execute("http://www.93.gov.cn/93app/data.do?channelId=0&startNum=0");
}
/**
* 设置轮播图
* @param lists 图片集合数据
*/
public void setBanner(List<Result.DataScrollEntity> lists){
if(lists==null){
return;
}
List<String> picPaths=new ArrayList<>();
for(int i=0;i<lists.size();i++){
Log.d("zzz",""+lists.get(i).getIMAGEURL());
picPaths.add("http://www.93.gov.cn"+lists.get(i).getIMAGEURL());
}
myBanner.setImages(picPaths);//设置图片集合
myBanner.setImageLoader(new MyBanner());//设置图片加载器
myBanner.isAutoPlay(true);//设置是否是自动播放
myBanner.setDelayTime(2000);//设置每张图片的播放的间隔时间
myBanner.start();//开始执行
}
/**
* 设置适配器
*/
public void setAdapter(){
if(myAdapter==null){
myAdapter=new MyAdapter(datas,getActivity());
listView.setAdapter(myAdapter);
}else{
myAdapter.notifyDataSetChanged();
}
}
/**
* 关闭刷新
*/
public void closeRefresh(){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
scrollView.onRefreshComplete();
}
},1000);
}
}
MainActivity
package com.example.week03_month;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioGroup;
import com.example.week03_month.fragment.FaxianFragment;
import com.example.week03_month.fragment.ShouyeFragment;
import com.example.week03_month.fragment.WodeFragment;
import com.example.week03_month.fragment.XiazaiFragment;
public class MainActivity extends AppCompatActivity {
private RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = (RadioGroup) findViewById(R.id.rel_navigate);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId==R.id.rb_index){
addFragment(new ShouyeFragment());
}else if(checkedId==R.id.rb_discovery){
addFragment(new FaxianFragment());
}else if(checkedId==R.id.rb_down){
addFragment(new XiazaiFragment());
}else if(checkedId==R.id.rb_me){
addFragment(new WodeFragment());
}
}
});
//默认添加"首页"
addFragment(new ShouyeFragment());
}
public void addFragment(Fragment fragment){
getSupportFragmentManager().beginTransaction().replace(R.id.main_content,fragment).commit();
}
}
adapter
MyAdapter
package com.example.week03_month.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.week03_month.R;
import com.example.week03_month.Result;
import com.example.week03_month.Utils.ImageloaderUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.List;
/**
* Created by ass on 2017/10/24.
*/
public class MyAdapter extends BaseAdapter {
private List<Result.DataEntity> datas;
private Context context;
private DisplayImageOptions options;
public MyAdapter(List<Result.DataEntity> datas, Context context) {
this.datas = datas;
this.context = context;
}
@Override
public int getCount() {
return datas.size();
}
@Override
public Object getItem(int position) {
return datas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView==null){
convertView=View.inflate(context, R.layout.item,null);
holder=new ViewHolder();
holder.tvTitle= (TextView) convertView.findViewById(R.id.tv_title);
holder.img= (ImageView) convertView.findViewById(R.id.img);
convertView.setTag(holder);
}else{
holder=(ViewHolder) convertView.getTag();
}
holder.tvTitle.setText(datas.get(position).getTITLE());
if(datas.get(position).getIMAGEURL()==null || datas.get(position).getIMAGEURL().equals("")){
holder.img.setImageResource(R.mipmap.ic_launcher);
}else{
//imageLoader加载图片
ImageLoader.getInstance().displayImage(datas.get(position).getIMAGEURL(),holder.img, ImageloaderUtil.getImageOptions());
}
return convertView;
}
class ViewHolder{
TextView tvTitle;
ImageView img;
}
}
MyPagerAdapter
package com.example.week03_month.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.example.week03_month.fragment.ContentFragment;
import java.util.List;
/**
* Created by ass on 2017/10/24.
*/
public class MyPagerAdapter extends FragmentPagerAdapter{
private List<String> titles;
public MyPagerAdapter(FragmentManager fm, List<String> titles) {
super(fm);
this.titles = titles;
}
//返回标题
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
@Override
public Fragment getItem(int position) {
//暂时返回“推荐页面”
return new ContentFragment();
}
@Override
public int getCount() {
return titles.size();
}
}
Result bean
MyListView
package com.example.week03_month;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* Created by ass on 2017/10/24.
*/
public class MyListView extends ListView{
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
MyTask
package com.example.week03_month.Utils;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by ass on 2017/10/24.
*/
public class MyTask extends AsyncTask<String,Void,String> {
//申请一个接口类对象
private Icallbacks icallbacks;
//将无参构造设置成私有的,使之在外部不能够调用
private MyTask(){}
//定义有参构造方法
public MyTask(Icallbacks icallbacks) {
this.icallbacks = icallbacks;
}
@Override
protected String doInBackground(String... params) {
String str="";
try {
//使用HttpUrlConnection
URL url=new URL(params[0]);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
if(connection.getResponseCode()==200){
InputStream inputStream=connection.getInputStream();
//调用工具类中的静态方法
str=StreamToString.streamToStr(inputStream,"utf-8");
}
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//解析,封装到bean,更新ui组件
icallbacks.updateUiByjson(s);
}
//定义一个接口
public interface Icallbacks{
/**
* 根据回传的json字符串,解析并更新页面组件
* @param jsonstr
*/
void updateUiByjson(String jsonstr);
}
}
StreamToString
package com.example.week03_month.Utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by ass on 2017/10/24.
*/
public class StreamToString {
public static String streamToStr(InputStream inputStream, String chartSet){
StringBuilder builder=new StringBuilder();
try {
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream,chartSet));
String con;
while ((con=br.readLine())!=null){
builder.append(con);
}
br.close();
return builder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
ImageloaderUtil
package com.example.week03_month.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.io.File;
/**
* Created by ass on 2017/10/24.
*/
public class ImageloaderUtil {
public static void initConfig(Context context) {
//配置
// File cacheFile=context.getExternalCacheDir();
File cacheFile= new File(Environment.getExternalStorageDirectory()+"/"+"imgages");
ImageLoaderConfiguration config=new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽
.threadPoolSize(2)//线程池的数量
.threadPriority(4)
.memoryCacheSize(2*1024*1024)//设置内存缓存区大小
.diskCacheSize(20*1024*1024)//设置sd卡缓存区大小
.diskCache(new UnlimitedDiskCache(cacheFile))//自定义缓存目录
.writeDebugLogs()//打印日志内容
.diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理
.build();
ImageLoader.getInstance().init(config);
}
/**
* 获取图片设置类
* @return
*/
public static DisplayImageOptions getImageOptions(){
DisplayImageOptions optionsoptions=new DisplayImageOptions.Builder()
.cacheInMemory(true)//使用内存缓存
.cacheOnDisk(true)//使用磁盘缓存
.bitmapConfig(Bitmap.Config.RGB_565)//设置图片格式
.build();
return optionsoptions;
}
}
MyApplication
package com.example.week03_month;
import android.app.Application;
import com.example.week03_month.Utils.ImageloaderUtil;
/**
* Created by ass on 2017/10/24.
*/
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//初使化
ImageloaderUtil.initConfig(this);
}
}
MD5Encoder
package com.example.week03_month.Utils;
import java.security.MessageDigest;
/**
* Created by ass on 2017/10/24.
*/
public class MD5Encoder {
public static String encode(String string) throws Exception {
byte[] hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) {
hex.append("0");
}
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
}
NetStateUtil(网络判断)
package com.example.week03_month.Utils;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.example.week03_month.R;
/**
* Created by ass on 2017/10/24.
*/
public class NetStateUtil {
/*
* 判断网络连接是否已开
* true 已打开 false 未打开
* */
public static boolean isConn(Context context){
boolean bisConnFlag=false;
ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = conManager.getActiveNetworkInfo();
if(network!=null){
bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();
}
return bisConnFlag;
}
/**
* 当判断当前手机没有网络时选择是否打开网络设置
* @param context
*/
public static void showNoNetWorkDlg(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.mipmap.ic_launcher) //
.setTitle(R.string.app_name) //
.setMessage("当前无网络").setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 跳转到系统的网络设置界面
Intent intent = null;
// 先判断当前系统版本
if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
}
context.startActivity(intent);
}
}).setNegativeButton("知道了", null).show();
}
}
MyBanner
package com.example.week03_month.Utils;
import android.content.Context;
import android.widget.ImageView;
import com.youth.banner.loader.ImageLoader;
/**
* Created by ass on 2017/10/24.
*/
public class MyBanner extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(path.toString(),imageView,ImageloaderUtil.getImageOptions());
}
}