欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

httpurlconnection,imageloder,xlistview,加分布局,网络求求,Viewpage实现fragment

程序员文章站 2022-05-11 23:13:23
...
package bwie.com.majunbao20180716.activity.activity;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioGroup;

import java.util.ArrayList;

import bwie.com.majunbao20180716.R;
import bwie.com.majunbao20180716.activity.adapter.MyFragmentAdapter;
import bwie.com.majunbao20180716.activity.fragment.Fragment1;
import bwie.com.majunbao20180716.activity.fragment.Fragment2;
import bwie.com.majunbao20180716.activity.fragment.Fragment3;

public class MainActivity extends AppCompatActivity {

    private ViewPager view_pager;
    private RadioGroup radio_group;
    private Fragment3 fragment3;
    private Fragment2 fragment2;
    private Fragment1 fragment1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        view_pager = (ViewPager) findViewById(R.id.view_pager);
        radio_group = (RadioGroup) findViewById(R.id.radio_group);
        //创建fragment
        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3();
        //创建集合
        ArrayList<Fragment> list = new ArrayList<>();
        list.add(fragment1);
        list.add(fragment2);
        list.add(fragment3);
        //创建适配器
        MyFragmentAdapter adapter=new MyFragmentAdapter(getSupportFragmentManager(),list);
        //添加到适配器
        view_pager.setAdapter(adapter);
        //点击改变当前页面
        radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId){
                    case R.id.rb1:
                        view_pager.setCurrentItem(0);
                        break;
                    case R.id.rb2:
                        view_pager.setCurrentItem(1);
                        break;
                    case R.id.rb3:
                        view_pager.setCurrentItem(2);
                        break;
                }
            }
        });
        //滑动改变fragment
        view_pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                radio_group.check(radio_group.getChildAt(position).getId());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
}
package bwie.com.majunbao20180716.activity.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by 我 on 2018/7/16.
 */

public class MyFragmentAdapter extends FragmentPagerAdapter{
    private List<Fragment> list;
    public MyFragmentAdapter(FragmentManager fm, List<Fragment> list) {
        super(fm);
        this.list = list;
    }

    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }

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

}

package bwie.com.majunbao20180716.activity.fragment;


import android.os.AsyncTask;
import android.os.Bundle;
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.google.gson.Gson;

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

import bwie.com.majunbao20180716.R;
import bwie.com.majunbao20180716.activity.adapter.MyAdapter;
import bwie.com.majunbao20180716.activity.bean.UserBean;
import bwie.com.majunbao20180716.activity.view.XListView;

/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment1 extends Fragment {


    private XListView xlistview;
    private int page=1;
    private String path="http://www.xieast.com/api/news/news.php?page=";
    private List<UserBean.DataBean> list=new ArrayList<>();
    private MyAdapter adapter;

    public Fragment1() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment1, container, false);
        xlistview = (XListView) view.findViewById(R.id.xlistview);
        return view;
    }
    //逻辑代码
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //xlistview配置
        xlist();
        //网络请求
       new MyAsycnTask().execute();

        //执行
    }

    private void xlist() {
        //下拉刷新
        xlistview.setPullRefreshEnable(true);
        //上拉加载
        xlistview.setPullLoadEnable(true);
        //监听
        xlistview.setXListViewListener(new XListView.IXListViewListener() {
            //下拉刷新
            @Override
            public void onRefresh() {
                page=1;
                new MyAsycnTask().execute();
            }
            //上拉加载
            @Override
            public void onLoadMore() {
                page+=1;
                new MyAsycnTask().execute();
            }
        });
        //创建适配器
        adapter = new MyAdapter(getActivity(), list);
        xlistview.setAdapter(adapter);

    }

    private class MyAsycnTask extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... params) {
            //定义路径
            String da=path+page;
            //网络请求
            try {
                URL url=new URL(da);
                Log.i("aaa",da);
                //获取网络请求
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //设置请求超时时间
                connection.setConnectTimeout(5000);
                //设置请求读取时间
                connection.setReadTimeout(5000);
                //设置求求方式
                connection.setRequestMethod("GET");
                //判断状态吗
                if (connection.getResponseCode()==200) {
                    InputStream inputStream = connection.getInputStream();
                    ByteArrayOutputStream bos=new ByteArrayOutputStream();
                    byte[] buffer=new byte[1024];
                    int len=0;
                    while ((len=inputStream.read(buffer))!=-1){
                        bos.write(buffer,0,len);
                    }
                    //关流
                    inputStream.close();
                    bos.close();
                    String s = bos.toString();
                    Log.i("aaa",s);
                    return s;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            UserBean userBean = gson.fromJson(s, UserBean.class);
            List<UserBean.DataBean> data = userBean.getData();
            if (page==1) {
                list.clear();
            }
            list.addAll(data);
            adapter.notifyDataSetChanged();
            if (page==1){
             xlistview.stopRefresh();
            }else{
                xlistview.stopLoadMore();
            }
        }
    }
}

package bwie.com.majunbao20180716.activity.adapter;

import android.content.Context;
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.ImageLoader;

import java.util.List;

import bwie.com.majunbao20180716.R;
import bwie.com.majunbao20180716.activity.bean.UserBean;

/**
 * Created by 我 on 2018/7/16.
 */

public class MyAdapter extends BaseAdapter{
    private static final int TYPE_0 = 0;
    private static final int TYPE_1 = 1;
    private Context context;
    private List<UserBean.DataBean> list;

    public MyAdapter(Context context, List<UserBean.DataBean> list) {
        this.context = context;
        this.list = list;
    }

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

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

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

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        String pc1 = list.get(position).getThumbnail_pic_s();
        String pc2 = list.get(position).getThumbnail_pic_s02();
        String pc3 = list.get(position).getThumbnail_pic_s03();
        if (pc1!=null&&pc2==null&&pc3==null) {
            return TYPE_0;
        }else {
            return TYPE_1;
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;
        int type = getItemViewType(position);
        Log.i("aaa",type+"123");
        if (convertView==null) {
            //有1个==0
            if (type==TYPE_0) {
                convertView = View.inflate(context, R.layout.item_adapter1, null);
                holder = new ViewHolder();
                holder.img1 = (ImageView) convertView.findViewById(R.id.img1);
                holder.text_author = (TextView) convertView.findViewById(R.id.text_author);
                holder.text_title = (TextView) convertView.findViewById(R.id.text_title);
                convertView.setTag(holder);
            }else {
                convertView = View.inflate(context, R.layout.item_adapter2, null);
                holder = new ViewHolder();
                holder.img2 = (ImageView) convertView.findViewById(R.id.img2);
                holder.img3 = (ImageView) convertView.findViewById(R.id.img3);
                holder.img4 = (ImageView) convertView.findViewById(R.id.img4);
                holder.text_author2 = (TextView) convertView.findViewById(R.id.text_author2);
                holder.text_title2 = (TextView) convertView.findViewById(R.id.text_title2);
                convertView.setTag(holder);
            }
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (type==TYPE_0){
            holder.text_title.setText(list.get(position).getTitle());
            holder.text_author.setText(list.get(position).getAuthor_name());
            ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(),holder.img1);
        }else {
            holder.text_title2.setText(list.get(position).getTitle());
            holder.text_author2.setText(list.get(position).getAuthor_name());
            ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(),holder.img2);
            ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s02(),holder.img3);
            ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s03(),holder.img4);
        }
        return convertView;
    }
    private class ViewHolder{
        ImageView img1,img2,img3,img4;
        TextView text_title,text_title2;
        TextView text_author,text_author2;
    }
}
package bwie.com.majunbao20180716.activity.application;

import android.app.Application;
import android.graphics.Bitmap;
import android.os.Environment;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LRULimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.File;

/**
 * Created by 我 on 2018/7/16.
 */

public class MyApplication extends Application{
    File path= new File(Environment.getExternalStorageDirectory()+"/"+"image");
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
                .defaultDisplayImageOptions(options())
                //大小
                .diskCacheExtraOptions(400,800,null)
                //个数
                .diskCacheFileCount(100)
                //分辨
                .diskCacheSize(50*1024*1024)
                .threadPoolSize(3)
                .memoryCache(new LRULimitedMemoryCache(2*1024*1024))
                //路径
                .diskCache(new UnlimitedDiskCache(path))
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .build();
        ImageLoader.getInstance().init(configuration);
    }

    private DisplayImageOptions options() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                //s设置色彩编码
                .bitmapConfig(Bitmap.Config.RGB_565)
                //设置下载图片是否显示在sd卡
                .cacheInMemory(true)
                .build();
        return options;
    }
}


相关标签: sa'