側滑+多條目+上拉載入+下拉重新整理+無限輪播+網路判斷
阿新 • • 發佈:2018-11-22
1.MainActivity頁面
package com.example.week2_02; import android.content.DialogInterface; import android.content.Intent; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.Toast; import com.example.Adaper.CountsAdaper; import com.example.Bean.BunnerBean; import com.example.Bean.NewsBean; import com.example.Util.NetUtil; import java.util.ArrayList; import java.util.List; import me.maxwin.view.XListView; public class MainActivity extends AppCompatActivity { private DrawerLayout layout; private ListView listView; private XListView xListView; private ActionBarDrawerToggle toggle; private String newUrl="http://172.17.8.100/movieApi/movie/v1/findHotMovieList?page=%d&count=%d"; private String bunnerUrl = "http://www.zhaoapi.cn/quarter/getAd"; private int mPage; private final int LOAD_COUNT =10; private CountsAdaper mAdaper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPage = 1; //獲取資源id layout = findViewById(R.id.draw); listView = findViewById(R.id.lv_list); xListView = findViewById(R.id.x_list); //建立介面卡 mAdaper = new CountsAdaper(this); //將介面卡設定給xlistview xListView.setAdapter(mAdaper); layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); if(!NetUtil.getInstance().hasNetWork(MainActivity.this)){ hasDialag(); return; } //支援重新整理 xListView.setPullRefreshEnable(true); //支援載入 xListView.setPullLoadEnable(true); //xlistview重新整理/載入監聽 xListView.setXListViewListener(new XListView.IXListViewListener() { //重新整理 @Override public void onRefresh() { mPage = 1; loadData(); } //載入 @Override public void onLoadMore() { mPage++; loadData(); } }); //左上角按鈕 inirBtn(); //側拉的值 inirData(); //載入資料 loadData(); } //載入資料 private void loadData() { if(mPage == 1){ //載入banner loadBanner(); //載入新聞 loadNew(); }else{ //載入新聞 loadNew(); } } //載入新聞 private void loadNew() { NetUtil.getInstance().getRequest(String.format(newUrl, mPage, LOAD_COUNT), NewsBean.class, new NetUtil.CallBack<NewsBean>() { @Override public void onSuccrss(NewsBean o) { if(mPage==1){ //重新整理 mAdaper.setmResult(o.getResult()); }else{ //載入 mAdaper.addmResult(o.getResult()); } //停止重新整理 xListView.stopRefresh(); //停止載入 xListView.stopLoadMore(); //判斷集合長度是否小於資料長度如果小於停止載入 if(o.getResult().size()<LOAD_COUNT){ xListView.setPullLoadEnable(false); } } }); } //載入banner private void loadBanner() { NetUtil.getInstance().getRequest(bunnerUrl, BunnerBean.class, new NetUtil.CallBack<BunnerBean>() { @Override public void onSuccrss(BunnerBean o) { mAdaper.setmData(o.getData()); } }); } //側拉的值 private void inirData() { final List<String> list = new ArrayList<>(); list.add("網易"); list.add("新浪"); list.add("頭條"); list.add("網易"); listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list)); //點選吐司 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this,list.get(position),Toast.LENGTH_SHORT).show(); } }); } //左上角按鈕 private void inirBtn() { ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); toggle = new ActionBarDrawerToggle(this,layout,R.string.open,R.string.close); toggle.syncState(); layout.addDrawerListener(toggle); } //判斷是否有網路彈框 public void hasDialag(){ new AlertDialog.Builder(this) .setTitle("無網路") .setMessage("當前網路不可用,是否去設定") .setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent("android.settings.WIRELESS_SETTINGS"); startActivity(intent); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } }
2.新聞bean
package com.example.Bean; import java.util.List; public class NewsBean { private List<ResultBean> result; public List<ResultBean> getResult() { return result; } public void setResult(List<ResultBean> result) { this.result = result; } public static class ResultBean { private boolean followMovie; private int id; private String imageUrl; private String name; private int rank; private String summary; public boolean isFollowMovie() { return followMovie; } public void setFollowMovie(boolean followMovie) { this.followMovie = followMovie; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } } }
3.輪播圖片Bean
package com.example.Bean; import java.util.List; public class BunnerBean { private List<DataBean> data; public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class DataBean { private int aid; private String createtime; private String icon; private Object productId; private String title; private int type; private String url; public int getAid() { return aid; } public void setAid(int aid) { this.aid = aid; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } //將https替換為http public String hasIcon(){ return icon.replace("https","http"); } public Object getProductId() { return productId; } public void setProductId(Object productId) { this.productId = productId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } }
4.內容介面卡
package com.example.Adaper;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
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 com.example.Bean.BunnerBean;
import com.example.Bean.NewsBean;
import com.example.week2_02.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class CountsAdaper extends BaseAdapter {
private List<BunnerBean.DataBean> mData;
private List<NewsBean.ResultBean> mResult;
private Context mContext;
private final int ITEM_COUNT = 2;
private final int BUNNER_TYPE =0;
private final int NEW_TYPE =1;
public CountsAdaper(Context mContext) {
this.mContext = mContext;
//初始化
mData = new ArrayList<>();
mResult = new ArrayList<>();
}
//判斷是否有banner
public boolean hasBanner(){
return mData.size()>0;
}
//重新整理Banner
public void setmData(List<BunnerBean.DataBean> datas){
mData.clear();
if(datas!=null){
//新增資料
mData.addAll(datas);
}
//重新整理介面卡
notifyDataSetChanged();
}
//重新整理新聞條目
public void setmResult(List<NewsBean.ResultBean> result){
mResult.clear();
if(result!=null){
//新增資料
mResult.addAll(result);
}
//重新整理介面卡
notifyDataSetChanged();
}
//下拉載入
public void addmResult(List<NewsBean.ResultBean> result){
if(result!=null){
//新增資料
mResult.addAll(result);
}
//重新整理介面卡
notifyDataSetChanged();
}
@Override
public int getCount() {
return hasBanner()?mResult.size()+1:mResult.size();
}
@Override
public NewsBean.ResultBean getItem(int position) {
return mResult.get(hasBanner()?position-1:position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getViewTypeCount() {
return ITEM_COUNT;
}
@Override
public int getItemViewType(int position) {
if(position == 0 && hasBanner()){
return BUNNER_TYPE;
}else{
return NEW_TYPE;
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(getItemViewType(position) == BUNNER_TYPE){
bunnerViewHelper helper;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.bunneritem,parent,false);
helper = new bunnerViewHelper(convertView);
}else{
helper = (bunnerViewHelper) convertView.getTag();
}
helper.bindBanner(mData);
}else{
newViewHolder holder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.newsitem,parent,false);
holder = new newViewHolder(convertView);
}else{
holder = (newViewHolder) convertView.getTag();
}
holder.bindNew(getItem(position));
}
return convertView;
}
//建立Bunner暫存器
class bunnerViewHelper{
ViewPager viewPager;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
handler.sendEmptyMessageDelayed(0,2000);
}
};
//獲取資源id
public bunnerViewHelper(View convertView) {
viewPager = convertView.findViewById(R.id.v_pager);
//設定tag
convertView.setTag(this);
}
//設定值
public void bindBanner(List<BunnerBean.DataBean> mData) {
handler.removeCallbacksAndMessages(null);
viewPager.setAdapter(new BannerAdaper(mData,mContext));
viewPager.setCurrentItem(viewPager.getAdapter().getCount()/2);
handler.sendEmptyMessageDelayed(0,2000);
}
}
//建立New暫存器
class newViewHolder{
ImageView image;
TextView title;
TextView summary;
//獲取資源id
public newViewHolder(View convertView) {
image = convertView.findViewById(R.id.image);
title = convertView.findViewById(R.id.title);
summary = convertView.findViewById(R.id.summary);
//設定tag
convertView.setTag(this);
}
//設定值
public void bindNew(NewsBean.ResultBean item) {
title.setText(item.getName());
summary.setText(item.getSummary());
ImageLoader.getInstance().displayImage(item.getImageUrl(),image);
}
}
}
5.輪播圖介面卡
package com.example.Adaper;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.Bean.BunnerBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.List;
public class BannerAdaper extends PagerAdapter {
private List<BunnerBean.DataBean> mData;
private Context context;
public BannerAdaper(List<BunnerBean.DataBean> mData, Context context) {
this.mData = mData;
this.context = context;
}
@Override
public int getCount() {
return 5000;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view==o;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
//建立ImageView
ImageView imageView = new ImageView(context);
//設定可拉伸
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//將imageview新增到ViewGroup
container.addView(imageView);
//設定圖片
ImageLoader.getInstance().displayImage(mData.get(position%mData.size()).hasIcon(),imageView);
return imageView;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
//刪除
container.removeView((View) object);
}
}
6.工具類
package com.example.Util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import com.google.gson.Gson;
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 NetUtil {
private static NetUtil instance;
private Gson gson;
public NetUtil() {
gson = new Gson();
}
//定義方法 獲取物件
public static NetUtil getInstance() {
if(instance == null){
instance = new NetUtil();
}
return instance;
}
//執行一個網路請求 返回string
public String getRequest(String urlSrt){
String json = "";
try {
//定義url地址
URL url = new URL(urlSrt);
//開啟連線
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//設定請求方式
urlConnection.setRequestMethod("GET");
//設定請求
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
//獲取請求碼
int responseCode = urlConnection.getResponseCode();
if(responseCode == 200){
json = stream2String(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
//將位元組流裝換為字元流
private String stream2String(InputStream inputStream) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
for(String tmp = br.readLine();tmp!=null;tmp = br.readLine()){
builder.append(tmp);
}
return builder.toString();
}
//執行一個網路請求返回bean
public <E> E getRequest(String urlSrt,Class clazz){
return (E) gson.fromJson(getRequest(urlSrt),clazz);
}
//定義介面
public interface CallBack<E>{
void onSuccrss(E e);
}
//回撥
@SuppressLint("StaticFieldLeak")
public void getRequest(String urlSrt, final Class clazz, final CallBack callBack){
new AsyncTask<String,Void,Object>(){
@Override
protected Object doInBackground(String... strings) {
return getRequest(strings[0],clazz);
}
@Override
protected void onPostExecute(Object o) {
callBack.onSuccrss(o);
}
}.execute(urlSrt);
}
//判斷是否有網路
public boolean hasNetWork(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo!=null&&activeNetworkInfo.isAvailable();
}
}
7.Application初始化圖片
package com.example;
import android.app.Application;
import android.graphics.Bitmap;
import com.example.week2_02.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
public class App extends Application {
@Override
public void onCreate() {
ImageLoader.getInstance().init(new ImageLoaderConfiguration.Builder(this)
//sdcard快取大小
.diskCacheSize(50*1024*1024)
//記憶體大小
.memoryCacheSizePercentage(13)
//設定圖片格式
.defaultDisplayImageOptions(new DisplayImageOptions.Builder()
//啟用外部快取
.cacheOnDisk(true)
//啟用內部快取
.cacheInMemory(true)
//設定色彩模式
.bitmapConfig(Bitmap.Config.ARGB_4444)
.showImageOnLoading(R.mipmap.ic_launcher)
.showImageOnFail(R.mipmap.ic_launcher)
.showImageForEmptyUri(R.mipmap.ic_launcher)
//設定圓角
.displayer(new RoundedBitmapDisplayer(16))
.build())
.build());
super.onCreate();
}
}
8.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.week2_02">
<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:name="com.example.App"
android:theme="@style/AppTheme">
<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>
9.佈局
<?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:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/draw"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<me.maxwin.view.XListView
android:id="@+id/x_list"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
/>
</android.support.constraint.ConstraintLayout>
<ListView
android:id="@+id/lv_list"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:background="#f00"
/>
</android.support.v4.widget.DrawerLayout>