MyTask工具类代码
public class MyTask extends AsyncTask{ //为借口提供有参构造 private ICallBeak iCallBeak; public MyTask(ICallBeak iCallBeak){ this.iCallBeak=iCallBeak; } @Override protected String doInBackground(String... strings) { try { URL url=new URL(strings[0]); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); urlConnection.setRequestMethod("GET"); int responseCode = urlConnection.getResponseCode(); if(responseCode==200){ InputStream inputStream = urlConnection.getInputStream(); String s = getTostring(inputStream); Log.d("--", "doInBackground: "+s); return s; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); iCallBeak.getJson(s);//调用 } //字符转换 private String getTostring(InputStream inputStream) { StringBuilder builder=new StringBuilder(); BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream)); String str; try { while((str=reader.readLine())!=null){ builder.append(str); } } catch (Exception e) { e.printStackTrace(); } return builder.toString(); } //定义接口 public interface ICallBeak{ void getJson(String json); } }
判断网络工具类
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(); } }
Applaction工具类
public class Applaction extends Application{ @Override public void onCreate() { super.onCreate(); //自定义sd卡缓存目录 File file=new File(Environment.getExternalStorageDirectory()+"/images"); //初始化,,全局配置applction ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this) .memoryCacheExtraOptions(400, 700)//缓存图片最大的长和宽 .threadPoolSize(3)//线程池的数量 .threadPriority(4) .memoryCacheSize(20*1024*1024)//设置内存缓存区大小 .diskCacheSize(80*1024*1024)//设置sd卡缓存区大小 .diskCache(new UnlimitedDiscCache(file))//自定义sd卡缓存目录 .writeDebugLogs()//打印日志内容 .diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理 .build(); ImageLoader.getInstance().init(configuration); } }
activity布局
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" xmlns:ptr="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.com.yue_kao.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="9" android:id="@+id/frame" > FrameLayout> <RadioGroup android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/group" android:orientation="horizontal"> <RadioButton android:layout_width="0dp" android:layout_height="wrap_content" android:id="@+id/but1" android:layout_weight="1" android:gravity="center" android:button="@null" android:checked="true" android:drawableTop="@drawable/image_selector" android:textColor="@color/text_color" android:text="首页" /> <RadioButton android:layout_width="0dp" android:layout_height="wrap_content" android:id="@+id/but2" android:layout_weight="1" android:gravity="center" android:button="@null" android:drawableTop="@drawable/image_selector2" android:textColor="@color/text_color" android:text="自选" /> <RadioButton android:layout_width="0dp" android:layout_height="wrap_content" android:id="@+id/but3" android:layout_weight="1" android:gravity="center" android:button="@null" android:drawableTop="@drawable/image_selector3" android:textColor="@color/text_color" android:text="行情" /> <RadioButton android:layout_width="0dp" android:layout_height="wrap_content" android:id="@+id/but4" android:layout_weight="1" android:gravity="center" android:button="@null" android:drawableTop="@drawable/image_selector4" android:textColor="@color/text_color" android:text="资讯" /> RadioGroup> LinearLayout> <LinearLayout android:layout_width="200dp" android:layout_height="match_parent" android:layout_gravity="start" android:background="#ff0" > <ImageView android:layout_width="100dp" android:layout_height="100dp" android:src="@drawable/w06"/> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/listview">ListView> LinearLayout> android.support.v4.widget.DrawerLayout>
MainActivity代码(页面切换)------------
public class MainActivity extends AppCompatActivity { private RadioGroup group; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //找到控件 getSupportFragmentManager().beginTransaction().replace(R.id.frame,new Fragment1()).commit(); group = findViewById(R.id.group); //为group设置监听 group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { switch(i){ case R.id.but1: getSupportFragmentManager().beginTransaction().replace(R.id.frame,new Fragment1()).commit(); break; case R.id.but2: getSupportFragmentManager().beginTransaction().replace(R.id.frame,new Fragment2()).commit(); break; case R.id.but3: getSupportFragmentManager().beginTransaction().replace(R.id.frame,new Fragment3()).commit(); break; case R.id.but4: getSupportFragmentManager().beginTransaction().replace(R.id.frame,new Fragment4()).commit(); break; default: break; } } }); } }
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" xmlns:app="http://schemas.android.com/apk/res-auto" android:background="#f89" android:orientation="vertical"> <android.support.design.widget.TabLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tab" app:tabGravity="center" app:tabIndicatorColor="@color/colorAccent" app:tabMode="scrollable" app:tabSelectedTextColor="@color/colorPrimaryDark" app:tabTextColor="@color/colorPrimary" > android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/pager">android.support.v4.view.ViewPager> LinearLayout>
Fragment1 代码----------
public class Fragment1 extends Fragment{ private ViewPager pager; private TabLayout tab; private Listlist; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragment01,container,false); //找到控件 pager = view.findViewById(R.id.pager); tab = view.findViewById(R.id.tab); //数据 requestData(); //为pager设置适配器 pager.setAdapter(new MyAdapter(getChildFragmentManager())); //绑定 tab.setupWithViewPager(pager); //一次加载所有数据 pager.setOffscreenPageLimit(list.size()); return view; } private void requestData() { list = new ArrayList<>(); list.add("数据新闻"); list.add("快讯"); list.add("头条"); list.add("精编公告"); list.add("美股"); list.add("港股"); list.add("基金"); list.add("理财"); } private class MyAdapter extends FragmentPagerAdapter { public MyAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { ContentFragment fragment=new ContentFragment(); Bundle bundle=new Bundle(); if(list.get(position).equals("数据新闻")){ bundle.putString("type","xbsjxw"); }else if(list.get(position).equals("快讯")){ bundle.putString("type","txs"); }else if(list.get(position).equals("头条")){ bundle.putString("type","toutiao"); }else if(list.get(position).equals("精编公告")){ bundle.putString("type","news/mobile/jbgg"); }else if(list.get(position).equals("美股")){ bundle.putString("type","news/mobile/mgxw"); }else if(list.get(position).equals("港股")){ bundle.putString("type","news/mobile/ggxw"); }else if(list.get(position).equals("基金")){ bundle.putString("type","news/mobile/jjxw"); }else if(list.get(position).equals("理财")){ bundle.putString("type","news/mobile/lcxw"); } fragment.setArguments(bundle); return fragment; } @Override public int getCount() { return list.size(); } @Override public CharSequence getPageTitle(int position) { return list.get(position); } } }
content_fragment布局----------------
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" xmlns:ptr="http://schemas.android.com/apk/res-auto" android:background="#f89"> <com.handmark.pulltorefresh.library.PullToRefreshListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/plist" ptr:ptrAnimationStyle="flip" ptr:ptrHeaderBackground="#383838" ptr:ptrHeaderTextColor="#FFFFFF" >com.handmark.pulltorefresh.library.PullToRefreshListView> LinearLayout>
ContentFragment代码--------------
public class ContentFragment extends Fragment{ private Listlist=new ArrayList<>(); private PullToRefreshListView plist; private int ptype=1; private String url; private String url1; private String type; private int index=1; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.content_fragment,container,false); //找到控件 plist = view.findViewById(R.id.plist); url = "http://mnews.gw.com.cn/wap/data/news/"; url1 = "/page_"+index+".json"; //得到bundle Bundle bundle = getArguments(); type = bundle.getString("type"); requestData();//进入加载数据 //为plist设置可上啦下拉 plist.setMode(PullToRefreshBase.Mode.BOTH); plist.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2 () { @Override public void onPullDownToRefresh(PullToRefreshBase pullToRefreshBase) { ptype=1; requestData(); } @Override public void onPullUpToRefresh(PullToRefreshBase pullToRefreshBase) { ptype=2; index++; requestData(); } }); return view; } private void requestData() { //异步加载 if(NetStateUtil.isConn(getActivity())){ MyTask myTask=new MyTask(new MyTask.ICallBeak() { @Override public void getJson(String json) { // Gson gson=new Gson(); List lists=new ArrayList<>(); try { JSONArray jsonArray = new JSONArray(json); JSONArray data = jsonArray.getJSONObject(0).getJSONArray("data"); for (int i = 0; i //创建对象 json bean=new json(); String img = data.getJSONObject(i).getString("img"); String otime = data.getJSONObject(i).getString("otime"); String title = data.getJSONObject(i).getString("title"); bean.setImg(img); bean.setOtime(otime); bean.setTitle(title); lists.add(bean); } } catch (Exception e) { e.printStackTrace(); } if(ptype==1){ list.clear(); } list.addAll(lists); //关闭头尾布局 new Handler().postDelayed(new Thread(new Runnable() { @Override public void run() { plist.onRefreshComplete(); } }),1000); //设置适配器 MyAdapter adapter=new MyAdapter(getActivity(),list); plist.setAdapter(adapter); } }); //请求 myTask.execute(url+type+url1); }else{ Toast.makeText(getActivity(),"亲,当前没有网络了呢",Toast.LENGTH_SHORT).show(); } } }
适配器代码
public class MyAdapter extends BaseAdapter{ private int ONE=0; private int TWO=1; private final DisplayImageOptions options; Context context; Listlist; public MyAdapter(Context context, List list) { this.context=context; this.list=list; options = new DisplayImageOptions.Builder() .cacheInMemory(true)//使用内存缓存 .cacheOnDisk(true)//使用磁盘缓存 .showImageOnLoading(R.mipmap.ic_launcher)//设置正在下载的图片 .showImageForEmptyUri(R.mipmap.ic_launcher)//url为空或请求的资源不存在时 .showImageOnFail(R.mipmap.ic_launcher)//下载失败时显示的图片 .bitmapConfig(Bitmap.Config.RGB_565)//设置图片色彩模式 1px=2字节 .imageScaleType(ImageScaleType.EXACTLY)//设置图片的缩放模式 //.displayer(new RoundedBitmapDisplayer(100))//设置圆角 30代表半径 自定义 .build(); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position){ String img = list.get(position).getImg(); if(img==null){ return ONE; }else{ return TWO; } } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { int type = getItemViewType(i); if(type==ONE){ ViewHolder holder; if(view==null){ view=View.inflate(context,R.layout.list_layout1,null); holder=new ViewHolder(); holder.image1=view.findViewById(R.id.image01); holder.text1=view.findViewById(R.id.text01); view.setTag(holder); }else{ holder= (ViewHolder) view.getTag(); } holder.image1.setImageResource(R.drawable.ic_launcher_background); holder.text1.setText(list.get(i).getTitle()); return view; }else{ ViewHolder2 holder2; if(view==null){ view=View.inflate(context,R.layout.list_layout2,null); holder2=new ViewHolder2(); holder2.image2=view.findViewById(R.id.image02); holder2.text2=view.findViewById(R.id.text02); view.setTag(holder2); }else{ holder2= (ViewHolder2) view.getTag(); } ImageLoader.getInstance().displayImage(list.get(i).getImg(),holder2.image2,options); holder2.text2.setText(list.get(i).getTitle()); return view; } } private class ViewHolder{ ImageView image1; TextView text1; } private class ViewHolder2{ ImageView image2; TextView text2; }
清单文件
xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.com.yue_kao"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" android:name=".Applaction"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> intent-filter> activity> application> manifest>