工具类(MyTask+NetUtils+MyApplication+MyAdapter+MyListView)


//请求网络的权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission//  加载MyApplication在清单文件中配置android:name="com.example.slx.utils.MyApplication"
//在build.gradle横向滑动需要配置
implementation 'com.android.support:design:26.+'
//在build.gradle上拉加载下拉刷新需要配置
compile 'com.github.userswlwork:pull-to-refresh:1.0.0' //横向滑动时,需要把根布局写成DrawerLayout,里面有主布   //局和菜单布局,在菜单布局中要有 android:layout_gravity="start",
在横向滑动中要有app:tabMode="scrollable"
 
//布局文件


<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com
/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-aut
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.slx.slx1_16.MainActivity"> <LinearLayout 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" android:id="@+id/myTab" app:tabMode="scrollable"> </android.support.design.widget.TabLayout> <com.handmark.pulltorefresh.library.PullToRefreshScrollView
android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/ps"> <com.example.slx.utils.MyListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listView"></com.example.slx.utils.MyListView> </com.handmark.pulltorefresh.library.PullToRefreshScrollView>
</LinearLayout>

<LinearLayout
android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="start" android:background="#f0f" >
<ListView
android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/listView_TabLayout" ></ListView>

</LinearLayout></android.support.v4.widget.DrawerLayout>


package com.example.slx.utils;


import android.os.AsyncTask;
import android.util.Log;

import com.example.slx.pojo.News;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lenovo on 2018/1/16.
 */

public class MyTask extends AsyncTask<String,Void,String>{
    private ICallBacks iCallBacks;
    private InputStream inputStream;

    public MyTask(ICallBacks iCallBacks) {
        this.iCallBacks = iCallBacks;
    }

    @Override
    protected String doInBackground(String... strings) {
        try {
            URL url = new URL(strings[0]);
            HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(2000);
            urlConnection.setReadTimeout(2000);
            Log.e("===============",urlConnection.getResponseCode()+"");
            if(urlConnection.getResponseCode()==200){
                inputStream = urlConnection.getInputStream();
            }else if(urlConnection.getResponseCode() == 301 || urlConnection.getResponseCode() == 302) {
                String location = urlConnection.getHeaderField("location");
                URL newurl = new URL(location);
                HttpURLConnection newurlConnection =(HttpURLConnection) newurl.openConnection();
                newurlConnection.setRequestMethod("GET");
                newurlConnection.setConnectTimeout(2000);
                newurlConnection.setReadTimeout(2000);
                if(newurlConnection.getResponseCode() == 200){
                    inputStream = newurlConnection.getInputStream();
                }
            }
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len=inputStream.read(bytes))!=-1){
                byteArrayOutputStream.write(bytes,0,len);
            }
            String s = byteArrayOutputStream.toString();
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        iCallBacks.getJson(s);
    }
    public interface ICallBacks{
        void getJson(String s);
    }
}



package com.example.slx.utils;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;

/**
 * Created by lenovo on 2018/1/12.
 */

public class NetUtils {
    //判断有无网络的方法
    public static boolean isConn(Context context){
        //1.得到系统服务
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        //2.得到网络信息类对象-需要添加权限

        //清单文件配置:
                NetworkInfo info = manager.getActiveNetworkInfo();
        //3.进行判断
        if(info!=null && info.isAvailable()){//已经连接网络
            return true;
        }else{
            return false;
        }
    }


    //如果没有网络的情况下,弹出一个对话框,打开设置页面
    public static void openNetDialog(final Context context){
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("提示");
        builder.setMessage("没有网络,是否进行设置?");
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //跳转到系统设置页面-隐士跳转
                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);
            }
        });
        builder.setNegativeButton("取消",null);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
package com.example.slx.utils;

import android.app.Application;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.File;

/**
 * Created by lenovo on 2018/1/13.
 */

public class MyApplication extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        File cachefile=getExternalCacheDir();
        ImageLoaderConfiguration config=new ImageLoaderConfiguration.Builder(this)
                .memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽
                .threadPoolSize(2)//线程池的数量
                .threadPriority(4)
                .memoryCacheSize(2*1024*1024)//设置内存缓存区大小
                .diskCacheSize(20*1024*1024)//设置sd卡缓存区大小
                .diskCache(new UnlimitedDiscCache(cachefile))//自定义缓存目录
                .writeDebugLogs()//打印日志内容
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理
                .build();
        ImageLoader.getInstance().init(config);



    }
}

package com.example.slx.Adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.slx.pojo.News;
import com.example.slx.slx1_17.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.List;

/**
 * Created by lenovo on 2018/1/17.
 */

public class MyAdapter extends BaseAdapter{
    private Context context;
    private List<News.DataBean> list;
    private DisplayImageOptions options;

    public MyAdapter(Context context, List<News.DataBean> 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)//设置图片色彩模式
                .imageScaleType(ImageScaleType.EXACTLY)//设置图片的缩放模式
                .build();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder;
        if(view==null){
            view=View.inflate(context, R.layout.item,null);
            holder=new ViewHolder();
            holder.textView=view.findViewById(R.id.textView);
            holder.imageView=view.findViewById(R.id.imageView);
            view.setTag(holder);
        }else {
            holder=(ViewHolder)view.getTag();
        }
        holder.textView.setText(list.get(i).getTitle());
        ImageLoader.getInstance().displayImage(list.get(i).getImg(),holder.imageView,options);
        return view;
    }
    public class ViewHolder{
        TextView textView;
        ImageView imageView;
    }
}

package com.example.slx.utils;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

/**
 * Created by lenovo on 2018/1/17.
 */

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 newHeight=MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec,newHeight );
    }
}



 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值