侧拉菜单

MainActivity

import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {

    private List<TabBean> lists=new ArrayList<TabBean>();
    private DrawerLayout drawerLayout;
    private LinearLayout linearLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

            ListView listView= (ListView) findViewById(R.id.lv);
            drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
            linearLayout = (LinearLayout) findViewById(R.id.menu);

            lists.add(new TabBean("新闻","1"));
            lists.add(new TabBean("关注","2"));
            lists.add(new TabBean("动态","3"));
            lists.add(new TabBean("设置","4"));

            listView.setAdapter(new MyAdapter(this,lists));

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //关闭侧滑菜单
                    drawerLayout.closeDrawer(linearLayout);
                    //只将 菜单 对应的类型 传过去
                    Bundle bundle=new Bundle();
                    bundle.putString("key",lists.get(position).getType());
                    ContentFragment cf=new ContentFragment();
                    cf.setArguments(bundle);
                    //动态添加一个fragment
                    getSupportFragmentManager().beginTransaction().replace(R.id.lin_content,cf).commit();
                }
            });
        }
}

MyAdapter

package com.example.weektest02;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class MyAdapter extends BaseAdapter{
    private Context context;
    private List<TabBean> datas;
    public MyAdapter(Context context, List<TabBean> datas) {
        this.context = context;
        this.datas = datas;

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

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolderTitle holderTitle;
        if(convertView==null){
            holderTitle=new ViewHolderTitle();
            convertView=View.inflate(context,R.layout.lv_item,null);
            holderTitle.tvTitle=(TextView) convertView.findViewById(R.id.tv);

            convertView.setTag(holderTitle);
        }else{
            holderTitle=(ViewHolderTitle) convertView.getTag();
        }

        holderTitle.tvTitle.setText(datas.get(position).getTitle());

        return  convertView;
    }

    class ViewHolderTitle{
        TextView tvTitle;
    }
}

StreamToString

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class StreamToString {
    public static String stream(InputStream inputStream,String chartSet){
        StringBuilder builder=new StringBuilder();
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(inputStream,chartSet));
            String con;
            while ((con=br.readLine())!=null){
                builder.append(con);
            }
            br.close();
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

TabBean

public class TabBean {
    private String title;
    private String type;

    public TabBean(String title, String type) {
        this.title = title;
        this.type = type;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

MyApplication

package com.example.weektest02;

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;

public class MyApplication extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        File externalCacheDir = getExternalCacheDir();
        ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this)
                .memoryCacheExtraOptions(480,800)
                .threadPoolSize(2)
                .threadPriority(4)
                .memoryCacheSize(5*1024*1024)
                .diskCacheSize(20*1024*1024)
                .diskCache(new UnlimitedDiscCache(externalCacheDir))
                .writeDebugLogs()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .build();
        ImageLoader.getInstance().init(configuration);

    }
}

MyLvAdapter

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

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.util.List;

public class MyLvAdapter extends BaseAdapter{
    private Context context;
    private List<Bean.DataBean> datas;

    //只有文本
    private final int NO_IMAGE = 0;
    //有图片且在右边
    private final int HAS_IMAGE = 1;

    //2.设置显示图片的类
    private DisplayImageOptions options;

    public MyLvAdapter(Context context, List<Bean.DataBean> datas) {
        this.context = context;
        this.datas = datas;

        //只需要初使化一次
        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)//设置图片显示的色彩模式
                .displayer(new RoundedBitmapDisplayer(20))//设置圆角图片
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                .build();
        // .imageScaleType() 设置图片的缩放方式的方法
    }
    //返回视图类型的个数
    @Override
    public int getViewTypeCount() {
        return 2;
    }

    //根据条目的下标,得到此条目到底应该是显示哪种类型视图,返回的是int
    @Override
    public int getItemViewType(int position) {

        String picUrl = datas.get(position).getPic_url();
        if (picUrl == null) {//无图片
            Log.d("zzz","无图片");
            return NO_IMAGE;

        } else {//有图片
            return HAS_IMAGE;
        }

    }

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

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        //根据position来显示条目的类型
        int type = getItemViewType(position);
        if (type == HAS_IMAGE) {
            ViewHolderImage holderImage;
            if (convertView == null) {
                holderImage = new ViewHolderImage();
                convertView = View.inflate(context, R.layout.lv_image, null);
                holderImage.tvTitle = (TextView) convertView.findViewById(R.id.tvtitle);
                holderImage.img = (ImageView) convertView.findViewById(R.id.img);

                convertView.setTag(holderImage);
            } else {
                holderImage = (ViewHolderImage) convertView.getTag();
            }

            //显示数据
            holderImage.tvTitle.setText(datas.get(position).getNews_title());
            //显示图片
            ImageLoader.getInstance().displayImage(datas.get(position).getPic_url(), holderImage.img, options);

        } else {

            ViewHolderTitle holderTitle;
            if (convertView == null) {
                holderTitle = new ViewHolderTitle();
                convertView = View.inflate(context, R.layout.lv_title, null);
                holderTitle.tvTitle = (TextView) convertView.findViewById(R.id.tv);

                convertView.setTag(holderTitle);
            } else {
                holderTitle = (ViewHolderTitle) convertView.getTag();
            }

            //显示数据
            holderTitle.tvTitle.setText(datas.get(position).getNews_title());

        }
        return convertView;
    }

    class ViewHolderTitle {
        TextView tvTitle;
    }

    class ViewHolderImage {
        ImageView img;
        TextView tvTitle;
    }
}

Bean

import java.util.List;


public class Bean {

    /**
     * error : false
     * results : [{"_id":"5a027569421aa90fe7253610","createdAt":"2017-11-08T11:09:29.236Z","desc":"免费专栏推荐:小米 MIUI 系统工程师 的《从源码角度看 Android》","publishedAt":"2017-11-10T08:10:02.838Z","source":"web","type":"Android","url":"https://mp.weixin.qq.com/s?__biz=MzU4MjAzNTAwMA==&mid=2247483816&idx=1&sn=9129a1fff64c6da7dde9143dc6995ec1&chksm=fdbf32ffcac8bbe943e81a23a487e3caac0dbb64e18509e61b28666074234c58e820b1a0aeea#rd","used":true,"who":null},{"_id":"5a02d0d1421aa90fe2f02c37","createdAt":"2017-11-08T17:39:29.976Z","desc":"这可能是第二好的自定义 View 教程之绘制","publishedAt":"2017-11-10T08:10:02.838Z","source":"web","type":"Android","url":"http://www.jianshu.com/p/7cea643df11b","used":true,"who":"LiuShilin"},{"_id":"5a0312a9421aa90fe7253615","createdAt":"2017-11-08T22:20:25.632Z","desc":"雕虫晓技(一) Android 组件化","publishedAt":"2017-11-10T08:10:02.838Z","source":"web","type":"Android","url":"https://mp.weixin.qq.com/s?__biz=MzI3MzMzNjgzMA==&mid=2247483674&idx=1&sn=fc93e05445a8fefcde0fdfb2c0145321&chksm=eb25918bdc52189d3ce82d7796ec95105927734d0cf47544126937d3d1255f41002f0cfb3afe&mpshare=1&scene=1&srcid=1106IA3DQP1u3IkOcCVwq1u2&key=5dba587a8b06ccca4ff30ff629f458ed05559774b37f3b9080982d26a7151db05c0324f15551f87029d3a11fee57d8fd51c5622f26b109f6f59a4c6c4ee811a840d7e9862b796b9dbdea8c14a1d32e9f&ascene=0&uin=NjM4NDkwNzgy&devicetype=iMac+MacBookAir7%2C2+OSX+OSX+10.12.4+build(16E195)&version=12010110&nettype=WIFI&fontScale=100&pass_ticket=wtm7nx0Fp2owsbSKcyoiIgV4pVu0Rw0GZicnXakuWo0tyipA8VCHAfpOkJGhp3yb","used":true,"who":"sloop"},{"_id":"5a03b2aa421aa90fe50c01e9","createdAt":"2017-11-09T09:43:06.493Z","desc":"我所理解的Android和iOS上的View","publishedAt":"2017-11-10T08:10:02.838Z","source":"web","type":"Android","url":"https://mp.weixin.qq.com/s/W9lRR4K3XRNTPvXf64qdhA","used":true,"who":"D_clock"},{"_id":"5a03ee2c421aa90fe7253619","createdAt":"2017-11-09T13:57:00.165Z","desc":"Kotlin 系列 - 从0到1 开发一个 App","images":["http://img.gank.io/35be6898-b5b8-4fa9-8b60-e49c6d6b998c"],"publishedAt":"2017-11-10T08:10:02.838Z","source":"web","type":"Android","url":"http://caimuhao.com/2017/11/02/Learn-Kotlin-While-Developing-An-Android-App-Introduction/","used":true,"who":null},{"_id":"5a041483421aa90fe2f02c3f","createdAt":"2017-11-09T16:40:35.807Z","desc":"那些年遇到的奇葩后台写的奇葩接口","publishedAt":"2017-11-10T08:10:02.838Z","source":"web","type":"Android","url":"http://www.jianshu.com/p/5a723f0b7c1e","used":true,"who":"阿韦"},{"_id":"5a000a51421aa90fef203504","createdAt":"2017-11-06T15:08:01.257Z","desc":" 使用CMake来进行Android NDK开发","publishedAt":"2017-11-08T11:00:50.559Z","source":"chrome","type":"Android","url":"http://blog.csdn.net/qq_34902522/article/details/78104610","used":true,"who":"宇宝守护神"},{"_id":"5a010bea421aa90fe7253604","createdAt":"2017-11-07T09:27:06.248Z","desc":"如何实现超萌动感小太阳?","publishedAt":"2017-11-08T11:00:50.559Z","source":"web","type":"Android","url":"https://mp.weixin.qq.com/s?__biz=MzIwMzYwMTk1NA==&mid=2247488057&idx=2&sn=d67b8d9c7da04e4efdec4084efe2098f","used":true,"who":"陈宇明"},{"_id":"5a0113a7421aa90fe7253605","createdAt":"2017-11-07T10:00:07.760Z","desc":"Android Gradle 自定义Task 详解","publishedAt":"2017-11-08T11:00:50.559Z","source":"web","type":"Android","url":"http://blog.csdn.net/zhaoyanjun6/article/details/76408024","used":true,"who":"赵彦军"},{"_id":"5a012636421aa90fe2f02c31","createdAt":"2017-11-07T11:19:18.496Z","desc":"教你如何在SDK开发使用美团Robust进行热更新","publishedAt":"2017-11-08T11:00:50.559Z","source":"web","type":"Android","url":"http://www.jianshu.com/p/9284853d5762","used":true,"who":"Ou Bowu"}]
     */

    private int status;
    private String info;
    private List<DataBean> data;

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        /**
         * news_id : 13811
         * news_title : 深港澳台千里连线,嘉年华会今夏入川
         * news_summary : 6月17—20日,“2016成都深港澳台嘉年华会”(简称嘉年华会)将在成都世纪城国际会展中心举办。其主办方励展华博借力旗
         * pic_url : http://f.expoon.com/sub/news/2016/01/21/887844_230x162_0.jpg
         */

        private String news_id;
        private String news_title;
        private String news_summary;
        private String pic_url;

        public String getNews_id() {
            return news_id;
        }

        public void setNews_id(String news_id) {
            this.news_id = news_id;
        }

        public String getNews_title() {
            return news_title;
        }

        public void setNews_title(String news_title) {
            this.news_title = news_title;
        }

        public String getNews_summary() {
            return news_summary;
        }

        public void setNews_summary(String news_summary) {
            this.news_summary = news_summary;
        }

        public String getPic_url() {
            return pic_url;
        }

        public void setPic_url(String pic_url) {
            this.pic_url = pic_url;
        }
    }
}

ContentFragment

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.weektest02.view.XListView;
import com.google.gson.Gson;

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


public class ContentFragment extends Fragment{
    String type="";

    private List<Bean.DataBean> lists=new ArrayList<>();
    private MyLvAdapter adapter;

    private String requestUrl;
    //第几页
    private int pageIndex=1;

    //1:刷新  2:加载
    private int operaType=1;

    private Handler myHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(operaType==1){
                xListView.stopRefresh();
                Date date = new Date(System.currentTimeMillis());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String s = sdf.format(date);
                xListView.setRefreshTime(s);

                //设置

            }else{
                xListView.stopLoadMore();
            }
        }
    };
    private XListView xListView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.fragment_layout,container,false);
        xListView = (XListView) v.findViewById(R.id.xlv);

        Bundle bundle=getArguments();

        type=bundle.getString("key");
        //拼接url地址
        requestUrl="http://api.expoon.com/AppNews/getNewsList/type/"+type+"/p/"+pageIndex;
        Log.d("zzz","type:"+type);


        return v;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        xListView.setPullLoadEnable(true);
        xListView.setPullRefreshEnable(true);

        xListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                operaType=1;
                pageIndex=1;

                new MyTesk().execute(requestUrl);
            }

            @Override
            public void onLoadMore() {
                operaType=2;
                pageIndex++;

                new MyTesk().execute(requestUrl);
            }
        });

        Log.d("zzz","url:"+requestUrl);
        //执行异步任务去请求
        new MyTesk().execute(requestUrl);




    }

    class MyTesk extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setReadTimeout(30000);
                connection.setReadTimeout(30000);
                int code = connection.getResponseCode();
                if (code == 200) {
                    InputStream inputStream = connection.getInputStream();
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while ((len = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                    outputStream.close();
                    inputStream.close();
                    String s = outputStream.toString();
                    return s;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            Bean user = gson.fromJson(s,Bean.class);

            if(operaType==1){
                //如果是刷新操作
                lists.clear();
            }

            //添加集合数据
            lists.addAll(user.getData());


            //设置适配器
            setAdapter();


            //关闭头部与尾部布局
            myHandler.sendEmptyMessageDelayed(0,1000);



        }
    }

    /**
     * 设备适配器
     */
    private void setAdapter() {
        if (adapter == null) {
            adapter = new MyLvAdapter(getActivity(),lists);
            xListView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else {
        }
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值