import android.content.Context; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.ljn.myapplication.R; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by HP on 2017/11/9. */ public class Utils { public static DisplayImageOptions getDisplayImageOption() { DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.mipmap.ic_launcher) //设置图片在下载期间显示的图片 .showImageForEmptyUri(R.mipmap.ic_launcher)//设置图片Uri为空或是错误的时候显示的图片 .showImageOnFail(R.mipmap.ic_launcher) //设置图片加载/解码过程中错误时候显示的图片 .cacheInMemory(true)//设置下载的图片是否缓存在内存中 .cacheOnDisk(true) .considerExifParams(true) //是否考虑JPEG图像EXIF参数(旋转,翻转) .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示 .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型// .displayer(new RoundedBitmapDisplayer(30))//是否设置为圆角,弧度为多少 // .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间 .build();//构建完成 return options; } public static String getNetString(String str){ try { URL url=new URL(str); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); int responseCode = urlConnection.getResponseCode(); if (responseCode==200){ InputStream is = urlConnection.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); StringBuilder sb=new StringBuilder(); String line=null; while ((line=br.readLine())!=null){ sb.append(line); } return sb.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } return null; } /** * 返回值 -1:没有网络 1:WIFI网络 2:net网络 //工具类 判断网络 */ public static int getNetype(Context context) { int netType = -1; ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo == null) { return netType; } int nType = networkInfo.getType(); if (nType == ConnectivityManager.TYPE_MOBILE) { netType = 2; } else if (nType == ConnectivityManager.TYPE_WIFI) { netType = 1; } return netType; } }
import android.app.Application; import android.os.Environment; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator; import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import java.io.File; /** * Created by HP on 2017/11/9. */ public class MApp extends Application { File cacheFile= new File(Environment.getExternalStorageDirectory()+"/"+"imgages"); @Override public void onCreate() { super.onCreate(); //初始化组件,链式开发思想,整个框架的参数初始化配置 ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this) .memoryCacheExtraOptions(480, 800) // default = device screen dimensions 内存缓存文件的最大长宽 .diskCacheExtraOptions(480, 800, null) // 本地缓存的详细信息(缓存的最大长宽),最好不要设置这个 .tasksProcessingOrder(QueueProcessingType.FIFO) // default .denyCacheImageMultipleSizesInMemory() .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现 .memoryCacheSize(2 * 1024 * 1024) // 内存缓存的最大值 .memoryCacheSizePercentage(13) // default .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值 .diskCacheFileCount(100) // 可以缓存的文件数量 .diskCache(new UnlimitedDiskCache(cacheFile))//自定义缓存目录 // default为使用HASHCODE对UIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密 .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default .writeDebugLogs() // 打印debug log .build(); ImageLoader.getInstance().init(configuration); } }
import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioGroup; import android.widget.Toast; import com.ljn.myapplication.fragment.MainFragment1; import com.ljn.myapplication.fragment.MainFragment2; import com.ljn.myapplication.fragment.MainFragment3; import com.ljn.myapplication.fragment.MainFragment4; import com.ljn.myapplication.utils.Utils; public class MainActivity extends AppCompatActivity { private FragmentManager manager; private MainFragment1 mainfragment1; private RadioGroup rg; private MainFragment2 mainfragment2; private MainFragment3 mainfragment3; private MainFragment4 mainfragment4; private DrawerLayout drawerLayout; private LinearLayout mlayout; private ImageView img; @Override protected void onResume() { super.onResume(); int netype = Utils.getNetype(MainActivity.this); if (netype == -1) { Toast.makeText(this, "当前网络异常,请做联网操作!", Toast.LENGTH_SHORT).show(); } else if (netype == 1) { Toast.makeText(this, "当前网络正常,正在使用WiFi网络", Toast.LENGTH_SHORT).show(); } else if (netype == 0) { Toast.makeText(this, "当前网络正常,正在使用运营商网络(3G/4G),请注意流量的使用", Toast.LENGTH_SHORT).show(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rg = (RadioGroup) findViewById(R.id.main_rg); drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); mlayout = (LinearLayout) findViewById(R.id.mlayout); manager = getSupportFragmentManager(); mainfragment1 = new MainFragment1(); img = (ImageView) findViewById(R.id.main_img); manager.beginTransaction().add(R.id.main_fl,mainfragment1).commit(); rg.setOnCheckedChangeListener(new Myoccl()); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drawerLayout.closeDrawer(mlayout); } }); drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { Log.e("LOG","我来啦" ); } @Override public void onDrawerClosed(View drawerView) { Log.e("LOG","我走啦" ); } @Override public void onDrawerStateChanged(int newState) { } }); } private class Myoccl implements RadioGroup.OnCheckedChangeListener { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { hideFragments(); switch (i){ case R.id.main_rb1: manager.beginTransaction().show(mainfragment1).commit(); break; case R.id.main_rb2: if (mainfragment2==null){ mainfragment2 = new MainFragment2(); manager.beginTransaction().add(R.id.main_fl,mainfragment2).commit(); }else{ manager.beginTransaction().show(mainfragment2).commit(); } break; case R.id.main_rb3: if (mainfragment3==null){ mainfragment3 = new MainFragment3(); manager.beginTransaction().add(R.id.main_fl,mainfragment3).commit(); }else{ manager.beginTransaction().show(mainfragment3).commit(); } break; case R.id.main_rb4: if (mainfragment4==null){ mainfragment4 = new MainFragment4(); manager.beginTransaction().add(R.id.main_fl,mainfragment4).commit(); }else{ manager.beginTransaction().show(mainfragment4).commit(); } break; } } } private void hideFragments() { if (mainfragment1!=null&&mainfragment1.isAdded()){ manager.beginTransaction().hide(mainfragment1).commit(); } if (mainfragment2!=null&&mainfragment2.isAdded()){ manager.beginTransaction().hide(mainfragment2).commit(); } if (mainfragment3!=null&&mainfragment3.isAdded()){ manager.beginTransaction().hide(mainfragment3).commit(); } if (mainfragment4!=null&&mainfragment4.isAdded()){ manager.beginTransaction().hide(mainfragment4).commit(); } } }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RadioGroup; import com.ljn.myapplication.R; /** * Created by HP on 2017/11/9. */ public class MainFragment1 extends Fragment{ private ViewPager vp; private RadioGroup rg; private View view; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.mainfragment1, container, false); vp = view.findViewById(R.id.mf1_vp); rg = view.findViewById(R.id.mf1_rg); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); vp.setAdapter(new MyAdapter(getChildFragmentManager())); vp.setOnPageChangeListener(new Mopcl()); rg.setOnCheckedChangeListener(new Moccl()); } private class MyAdapter extends FragmentPagerAdapter { public MyAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position){ case 0: ChildFragment1 childFragment1 = new ChildFragment1(); return childFragment1; case 1: ChildFragment2 childFragment2 = new ChildFragment2(); return childFragment2; } return null; } @Override public int getCount() { return 2; } } private class Mopcl implements ViewPager.OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position){ case 0: RadioButton rb1 = view.findViewById(R.id.mf1_rb1); rb1.setChecked(true); break; case 1: RadioButton rb2 = view.findViewById(R.id.mf1_rb2); rb2.setChecked(true); break; } } @Override public void onPageScrollStateChanged(int state) { } } private class Moccl implements RadioGroup.OnCheckedChangeListener { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { int flag=0; switch (i){ case R.id.mf1_rb1: flag=0; break; case R.id.mf1_rb2: flag=1; break; } vp.setCurrentItem(flag); } } }
import android.os.AsyncTask; 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 android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bwie.xlistviewlibrary.View.XListView; import com.google.gson.Gson; import com.ljn.myapplication.R; import com.ljn.myapplication.bean.NewsBean; import com.ljn.myapplication.utils.Utils; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.ArrayList; import java.util.List; /** * Created by HP on 2017/11/10. */ public class ChildFragment1 extends Fragment implements XListView.IXListViewListener{ private int count=0; private String NetString="http://www.93.gov.cn/93app/data.do?channelId=0&startNum="+count; private List<NewsBean.DataBean> list=new ArrayList<NewsBean.DataBean>(); private MyAdapter adapter; private ImageLoader instance; private XListView xlistview; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.childfragment1, container, false); xlistview = view.findViewById(R.id.xlistview); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); instance = ImageLoader.getInstance(); getNetData(); adapter = new MyAdapter(); xlistview.setAdapter(adapter); xlistview.setPullLoadEnable(true); //让XListView有上拉加载的功能; xlistview.setXListViewListener(this); } private void getNetData() { new MyAsyncTask().execute(NetString); } private class MyAsyncTask extends AsyncTask<String,Void,String> { @Override protected String doInBackground(String... strings) { return Utils.getNetString(strings[0]); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson=new Gson(); NewsBean json = gson.fromJson(s, NewsBean.class); //得到集合; List<NewsBean.DataBean> data = json.getData(); //把从网络解析的数据放到adapter使用的集合里; list.addAll(data); adapter.notifyDataSetChanged(); uiComplete();// 让刷新头 或者刷新底部ui返回; } } private class MyAdapter extends BaseAdapter { private ViewHolder vh; private VHolder vholder; private TextView FROMNAME; private TextView SUBTITLE; private TextView TITLE; private ImageView IMAGEURL; @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public int getItemViewType(int position) { //根据图片是否为空进行判断 int flag=0; if (list.get(position).getIMAGEURL()==null){ flag=0; }else if (list.get(position).getIMAGEURL()!=null){ flag=1; } return flag; } @Override public int getViewTypeCount() { //getview里有几个布局就写几 return 2; } @Override public View getView(int i, View view, ViewGroup viewGroup) { //根据getItemViewType的返回值进行判断加载布局 int type = getItemViewType(i); switch (type){ case 0: if (view==null){ vholder = new VHolder(); view = View.inflate(getActivity(), R.layout.item1, null); view.setTag(vholder); }else{ vholder = (VHolder) view.getTag(); } vholder.FROMNAME = view.findViewById(R.id.item_FROMNAME); vholder.SUBTITLE = view.findViewById(R.id.item_SUBTITLE); vholder.TITLE = view.findViewById(R.id.item_TITLE); vholder.FROMNAME.setText(list.get(i).getFROMNAME()); vholder.SUBTITLE.setText(list.get(i).getSUBTITLE()); vholder.TITLE.setText(list.get(i).getTITLE()); break; case 1: if (view==null){ vh = new ViewHolder(); view = View.inflate(getActivity(), R.layout.item, null); view.setTag(vh); }else{ vh = (ViewHolder) view.getTag(); } vh.FROMNAME = view.findViewById(R.id.item_FROMNAME); vh.SUBTITLE = view.findViewById(R.id.item_SUBTITLE); vh.TITLE = view.findViewById(R.id.item_TITLE); vh.IMAGEURL = view.findViewById(R.id.item_IMAGEURL); vh.FROMNAME.setText(list.get(i).getFROMNAME()); vh.SUBTITLE.setText(list.get(i).getSUBTITLE()); vh.TITLE.setText(list.get(i).getTITLE()); instance.displayImage(list.get(i).getIMAGEURL(),vh.IMAGEURL, Utils.getDisplayImageOption()); break; } return view; } } //优化布局 class ViewHolder{ TextView FROMNAME; TextView SUBTITLE; TextView TITLE; ImageView IMAGEURL; } //优化布局 class VHolder{ TextView FROMNAME; TextView SUBTITLE; TextView TITLE; } /** * 下拉刷新 */ @Override public void onRefresh() { count=0; list.clear(); getNetData(); Toast.makeText(getActivity(),count+" ", Toast.LENGTH_LONG).show(); } /** * 上拉加载 */ @Override public void onLoadMore() { count+=20; getNetData(); Toast.makeText(getActivity(),count+" ",Toast.LENGTH_LONG).show(); } /** * 让刷新头 或者刷新底部ui返回; */ private void uiComplete(){ xlistview.stopRefresh();//停止刷新 xlistview.stopLoadMore();//停止上拉加载更多 xlistview.setRefreshTime("刚刚"); } }<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/drawerLayout" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.ljn.myapplication.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <FrameLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/main_fl" > </FrameLayout> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:id="@+id/main_rg" > <RadioButton android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:button="@null" android:text="首页" android:background="@drawable/selected" android:gravity="center_horizontal" android:id="@+id/main_rb1" /> <RadioButton android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:button="@null" android:text="掏" android:background="@drawable/selected" android:gravity="center_horizontal" android:id="@+id/main_rb2" /> <RadioButton android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:button="@null" android:text="搜索" android:background="@drawable/selected" android:gravity="center_horizontal" android:id="@+id/main_rb3" /> <RadioButton android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:button="@null" android:text="我的" android:background="@drawable/selected" android:gravity="center_horizontal" android:id="@+id/main_rb4" /> </RadioGroup> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"//实现侧滑 android:layout_gravity="left" android:choiceMode="singleChoice" android:id="@+id/mlayout" > <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:id="@+id/main_img" android:src="@drawable/i" /> </LinearLayout> </android.support.v4.widget.DrawerLayout>//childFragment1的布局<?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="vertical" > <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:id="@+id/mf1_rg" > <RadioButton android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:button="@null" android:text="实时新闻" android:background="@drawable/selected" android:gravity="center_horizontal" android:id="@+id/mf1_rb1" /> <RadioButton android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:button="@null" android:text="猜 猜 猜" android:background="@drawable/selected" android:gravity="center_horizontal" android:id="@+id/mf1_rb2" /> </RadioGroup> <android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/mf1_vp" /> </LinearLayout>//item getview加载的布局<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="200px" android:layout_height="200px" android:src="@mipmap/ic_launcher" android:id="@+id/item_IMAGEURL" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1" android:layout_marginTop="40px" android:id="@+id/item_FROMNAME" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2" android:layout_marginTop="15px" android:id="@+id/item_SUBTITLE" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="3" android:layout_marginTop="15px" android:id="@+id/item_TITLE" /> </LinearLayout> </LinearLayout>
在清单文件中配置
//网络状态<uses-permission android:name="android.permission.INTERNET" />//sd读写权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>//判断wifi状态 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />在application中配置android:name=".Mapp"在build.grable下配置compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.google.code.gson:gson:2.2.4'implementation project(':xlistviewlibrary')//添加xlistviewlibrary项目
判断网络状态 fragment隐藏显示 xlistview多条目加载数据
最新推荐文章于 2020-04-19 15:41:48 发布