例题:
导入XListView工具类:{File>ImportModule...>导入工具类地址》》》》导完之后右键需要用到工具类的工程>Open Module Settings>Dependencies>工具类>确定OK}
=========================================================
libs文件夹下加入jar包(导包): gson 和 universal-image-loader
=======================================
添加权限:
网络请求权限:INTERNET
<uses-permission android:name="android.permission.INTERNET"/>
网络判断权限:ACCESS_NETWORK_STATE
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
===========================================================
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.shenhuiran.MainActivity"> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="200dp"/> <com.bawei.jane.mxlistview.view.XListView android:id="@+id/xlistview" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> =================================================================== jesn解析:
MypagerBean 解析类
import java.util.List; public class MypagerBean {
https://api.tianapi.com/wxnew/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10&page=1
}
---------------------------------------------------------------------------
MyShuJu 解析类
import java.util.List; public class MyShuJu {
http://api.tianapi.com/tiyu/?key=36bafe109f1b68cc2c3829db69c7c180&num=
}
======================================================
主要代码:
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bawei.jane.mxlistview.view.XListView;
import com.example.shenhuiran.MyBean.MyShuJu;
import com.example.shenhuiran.MyBean.MypagerBean;
import com.example.shenhuiran.Utils.ImageLoaderutils;
import com.example.shenhuiran.Utils.MyNetTask;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<MyShuJu.NewslistBean> data = new ArrayList<>();
private List<String> list = new ArrayList<>();
private XListView xlistview;
private ViewPager viewPager;
private String part= "http://api.tianapi.com/tiyu/?key=36bafe109f1b68cc2c3829db69c7c180&num=";
private int index = 3;
private String url=part+index;
private int type=1;
private DisplayImageOptions option;
private Myadapter myadapter;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what == 0){
int currentItem = viewPager.getCurrentItem();
viewPager.setCurrentItem(currentItem+1);
handler.sendEmptyMessageDelayed(0,2000);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化图片
ImageLoaderutils.initImageLoader(MainActivity.this);
option = ImageLoaderutils.getImageOption(MainActivity.this);
//找控件
xlistview = findViewById(R.id.xlistview);
viewPager = findViewById(R.id.viewpager);
//viewpager
Newviewpager();
//xlistview
NewXlistview();
//xlistview获取参数与实例化适配器
requestData();
}
//xlistview相关操作
private void NewXlistview() {
xlistview.setPullRefreshEnable(true);
xlistview.setPullLoadEnable(true);
xlistview.setXListViewListener(new XListView.IXListViewListener() {
@Override
public void onRefresh() {
index=3;
url=part+index;
type=1;
requestData();
}
@Override
public void onLoadMore() {
index++;
url=part+index;
type=2;
requestData();
}
});
//XListView的长摁事件
xlistview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("url",data.get(position-1).getUrl());
startActivity(intent);
return true;
}
});
}
//xlistview获取参数与实例化适配器
private void requestData() {
MyNetTask task = new MyNetTask(new MyNetTask.IcallBack() {
@Override
public void getJsonData(String jsonStr) {
Gson gson = new Gson();
MyShuJu myShuJu = gson.fromJson(jsonStr, MyShuJu.class);
if (type==1)
{
data.clear();
}
data.addAll(myShuJu.getNewslist());
if (myadapter==null)
{
myadapter = new Myadapter();
xlistview.setAdapter(myadapter);
}else {
myadapter.notifyDataSetChanged();
}
if (type==1)
{
xlistview.stopRefresh();
}else {
xlistview.stopLoadMore();
}
}
});
task.execute(url);
}
//viewpager相关操作
private void Newviewpager() {
MyNetTask task = new MyNetTask(new MyNetTask.IcallBack() {
@Override
public void getJsonData(String jsonStr) {
Gson gson = new Gson();
MypagerBean myShuJu = gson.fromJson(jsonStr, MypagerBean.class);
List<MypagerBean.NewslistBean> newslist = myShuJu.getNewslist();
for (int i = 0 ;i<newslist.size();i++){
String picUrl = newslist.get(i).getPicUrl();
list.add(picUrl);
}
viewPager.setAdapter(new MyPagerAdapter());
viewPager.setCurrentItem(list.size()*10000);
handler.sendEmptyMessageDelayed(0,2000);
}
});
task.execute("https://api.tianapi.com/wxnew/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10&page=1");
}
//ViewPager的适配器
class MyPagerAdapter extends PagerAdapter{
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(MainActivity.this);
ImageLoader.getInstance().displayImage(list.get(position%list.size()),imageView,option);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
}
//xlistview的适配器
class Myadapter extends BaseAdapter{
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
if(position%2==0){
return 0;
}else{
return 1;
}
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
int itemViewType = getItemViewType(i);
if(itemViewType == 0){
ViewHolder0 holder0;
if(view == null){
view = View.inflate(MainActivity.this,R.layout.listview0,null);
holder0= new ViewHolder0();
holder0.tu = view.findViewById(R.id.tu_list0);
holder0.name = view.findViewById(R.id.name_list0);
view.setTag(holder0);
}else{
holder0 = (ViewHolder0) view.getTag();
}
ImageLoader.getInstance().displayImage(data.get(i).getPicUrl(),holder0.tu,option);
holder0.name.setText(data.get(i).getTitle());
}else{
ViewHolder1 holder1;
if(view == null){
view = View.inflate(MainActivity.this,R.layout.listview1,null);
holder1= new ViewHolder1();
holder1.name = view.findViewById(R.id.name_list1);
view.setTag(holder1);
}else{
holder1 = (ViewHolder1) view.getTag();
}
holder1.name.setText(data.get(i).getTitle());
}
return view;
}
class ViewHolder0{
ImageView tu;
TextView name;
}
class ViewHolder1{
TextView name;
}
}
}
-----------------------------------------------------------
两个布局:
R.layout.listview0
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/tu_list0" android:layout_width="100dp" android:layout_height="100dp" /> <TextView android:id="@+id/name_list0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_toEndOf="@+id/tu_list0" android:layout_toRightOf="@+id/tu_list0" android:padding="10dp" android:textSize="20sp" android:textColor="#f00" /> </RelativeLayout> --------------------------------------------
R.layout.listview1
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/name_list1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:padding="10dp" android:textSize="20sp" android:textColor="#f00" /> </RelativeLayout>
==============================================================
ImageLoaderutils 类
import android.content.Context; import android.graphics.Bitmap; import android.os.Environment; import com.example.shenhuiran.R; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache; 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.ImageScaleType; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; import com.nostra13.universalimageloader.core.download.BaseImageDownloader; import java.io.File; public class ImageLoaderutils { //初使化 public static void initImageLoader(Context context){ //自定义磁盘缓存路径 系统默认的缓存路径 sd...<package>..cache 当app被卸载时,此路径下的缓存图片一并被删除 //File cacheDir=getExternalCacheDir(); File cacheDir= new File(Environment.getExternalStorageDirectory().getPath()+"/aaa");//自定义 sd卡的缓存路径 //第一步:对ImageLoader进行初使化 ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(context) .memoryCacheExtraOptions(320, 450) // default = device screen dimensions 内存缓存文件的最大长宽 .diskCacheExtraOptions(480, 800, null) // 本地缓存的详细信息(缓存的最大长宽),最好不要设置这个 .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级 .tasksProcessingOrder(QueueProcessingType.FIFO) // default .denyCacheImageMultipleSizesInMemory() .memoryCache(new LruMemoryCache(10 * 1024 * 1024)) //可以通过自己的内存缓存实现 .memoryCacheSize(2 * 1024 * 1024) // 内存缓存的最大值 .memoryCacheSizePercentage(13) // default .diskCache(new UnlimitedDiscCache(cacheDir)) // 磁盘缓存 --default 可以自定义缓存路径 .diskCacheSize(20 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值 .diskCacheFileCount(100) // 可以缓存的文件数量 // default为使用HASHCODE对UIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密 .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) .imageDownloader(new BaseImageDownloader(context)) // default .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default .writeDebugLogs() // 打印debug log .build(); ImageLoader.getInstance().init(configuration); } //得到图片的显示设置类对象 public static DisplayImageOptions getImageOption(Context context){ DisplayImageOptions 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)//设置图片色彩模式 .imageScaleType(ImageScaleType.EXACTLY)//设置图片的缩放模式===imageView,,ScaleType .displayer(new RoundedBitmapDisplayer(50))//设置图片圆角显示 弧度 .build(); return options; } } ==================================================================
MyNetTask 类
import android.os.AsyncTask; 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; public class MyNetTask extends AsyncTask<String,Void,String> { //2.申明接口对象 private IcallBack icallBack; //3.创建构造方法,将接口传进来 public MyNetTask(IcallBack icallBack) { this.icallBack = icallBack; } @Override protected String doInBackground(String... strings) { StringBuilder builder=new StringBuilder(); //1.根据url创建URL try { URL url=new URL(strings[0]); //2.打开连接 HttpURLConnection conn =(HttpURLConnection) url.openConnection(); //3.设置 conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); //4.判断结果码 int responseCode = conn.getResponseCode(); if(conn.getResponseCode()==200){ //5.获取数据 InputStream inputStream = conn.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream)); String str; while ((str=reader.readLine())!=null){ builder.append(str); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); //4.调用接口中方法 icallBack.getJsonData(s); } //1.定义一个接口 public interface IcallBack{ void getJsonData(String jsonStr); } }
==================================================================
Main2Activity 类
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
WebView web = findViewById(R.id.Web);
Intent intent = getIntent();
String url = intent.getStringExtra("url");
//设置WebView属性,能够执行Javascript脚本
web.getSettings().setJavaScriptEnabled(true);
//加载需要显示的网页
web.loadUrl(url);
web.setWebViewClient(new HelloWebViewClient ());
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
---------------------------------------------
布局:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.shenhuiran.MainActivity"> <WebView android:id="@+id/Web" android:layout_width="match_parent" android:layout_height="match_parent"/> </android.support.constraint.ConstraintLayout>
========================================================
Wangluo 类
import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class Wangluo { public static boolean isConn(Context context){ ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info =(NetworkInfo) manager.getActiveNetworkInfo(); if(info!=null && info.isAvailable()){ return true; } return false; } public static void openDg(final Context context){ AlertDialog.Builder builder=new AlertDialog.Builder(context); builder.setMessage("是否要进行网络连接设置?"); builder.setPositiveButton("设置", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent=null; //判断手机系统的版本 即API大于10 就是3.0或以上版本 if(android.os.Build.VERSION.SDK_INT>10){ intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); }else{ intent = new Intent(); ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings"); intent.setComponent(component); intent.setAction("android.intent.action.VIEW"); } context.startActivity(intent); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.create().show(); } } ================================================================
MyBannerLoader类
import android.content.Context; import android.widget.ImageView; import com.nostra13.universalimageloader.core.ImageLoader; public class MyBannerLoader extends ImageLoader { public void displayImage(Context context, Object path, ImageView imageView) { ImageLoader.getInstance(). displayImage(path.toString(),imageView, ImageLoaderutils.getImageOption(context)); } }