网络判断+网络请求+TabLayout+XListview+多条目加载.

示例图
这里写图片描述
添加权限


添加依赖库
xlistview
TabLayout的依赖
布局
主activity布局

<RelativeLayout 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:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.sweek02.MainActivity">

    <RadioGroup
        android:id="@+id/rel_navigate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rb_shouye"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rb_selector"
            android:button="@null"
            android:checked="true"
            android:gravity="center"
            android:padding="3dp"
            android:text="首页" />

        <RadioButton
            android:id="@+id/rb_xiangfa"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rb_selector"
            android:button="@null"
            android:gravity="center"
            android:padding="3dp"
            android:text="想法" />

        <RadioButton
            android:id="@+id/rb_shichang"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rb_selector"
            android:button="@null"
            android:gravity="center"
            android:padding="3dp"
            android:text="市场" />

        <RadioButton
            android:id="@+id/rb_tongzhi"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rb_selector"
            android:button="@null"
            android:gravity="center"
            android:padding="3dp"
            android:text="通知" />

        <RadioButton
            android:id="@+id/rb_gengduo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/rb_selector"
            android:button="@null"
            android:gravity="center"
            android:padding="3dp"
            android:text="更多" />
    </RadioGroup>
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/rel_navigate"
    android:id="@+id/fr"
    android:layout_marginTop="50dp"
    ></FrameLayout>
<EditText
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/ed"
    android:layout_alignParentTop="true"
    android:hint="搜索"
    />
</RelativeLayout>

shouye布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        app:tabGravity="center"
        app:tabIndicatorColor="@color/colorAccent"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@color/colorPrimaryDark"
        app:tabTextColor="@color/colorPrimary"
        android:id="@+id/mytab"></android.support.design.widget.TabLayout>
    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/vp"></android.support.v4.view.ViewPager>
</LinearLayout>

fragmens

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tv"
    android:textSize="30sp"
    android:textColor="#f0f"
    />
</LinearLayout>

dongtai和faxian布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#f95"
    android:textSize="30dp"
    android:text="动态"
    />
</LinearLayout>

remen布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<com.example.sweek02.view.XListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/xlv"
    ></com.example.sweek02.view.XListView>
</LinearLayout>

多条目布局自己写
xlistview布局复制
Activity方法

public class MainActivity extends AppCompatActivity {
    private RadioGroup rg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rg = (RadioGroup) findViewById(R.id.rel_navigate);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId){
                    case R.id.rb_shouye:
                        getSupportFragmentManager().beginTransaction().replace(R.id.fr,new Shouye()).commit();
                        break;
                    case R.id.rb_xiangfa:
                        addFragment("想法");
                        break;
                    case R.id.rb_shichang:
                        addFragment("市场");
                        break;
                    case R.id.rb_tongzhi:
                        addFragment("通知");
                        break;
                    case R.id.rb_gengduo:
                        addFragment("更多");
                        break;
                }
            }
        });
        getSupportFragmentManager().beginTransaction().replace(R.id.fr,new Shouye()).commit();

    }
    public void addFragment(String str){
        Bundle bundle = new Bundle();
        bundle.putString("key",str);
        Fragmens fragmens = new Fragmens();
        fragmens.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().replace(R.id.fr,fragmens).commit();

    }
}

shouyeFragment

public class Shouye extends Fragment {
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private List<String> lists=new ArrayList<String>();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.shouye, container, false);
        viewPager = (ViewPager) v.findViewById(R.id.vp);
        tabLayout = (TabLayout) v.findViewById(R.id.mytab);

        //tab标题信息
        intTabData();
        //设置适配器 ,,得到子fragment的管理者,使用getChildFragmentManager
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
        //建立关联
        tabLayout.setupWithViewPager(viewPager);
        //指定加载的页数 http://blog.csdn.net/qq_29134495/article/details/51548002
        viewPager.setOffscreenPageLimit(lists.size());
        return v;
    }
    private void intTabData() {
        lists.add("动态");
        lists.add("热门");
        lists.add("发现");


    }
    class  MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        //获取tab导航文本
        @Override
        public CharSequence getPageTitle(int position) {
            return lists.get(position);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment =null;

            switch (position){
                case 0:
                    fragment = new Dongtai();
                    break;
                case 1:
                    fragment = new Remen();
                    break;
                case 2:
                    fragment = new Faxian();
                    break;

                default:
                    break;
            }

            return fragment;
        }

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

Fragmens

   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragmens, container, false);
        TextView tv = (TextView) v.findViewById(R.id.tv);
        Bundle bundle = getArguments();
        tv.setText(bundle.getString("key"));
        return v;
    }

faixan和dongtai的布局

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.faxian, container, false);
        return v;
    }

复制xlistview代码导进去
remen

public class Remen extends Fragment {
    private List<Resulte.ResultsBean> list=new ArrayList<>();

    private XListView xlv;
    private  int page=1;
    private  int   type=1;
    private  String url="http://gank.io/api/data/Android/10/"+page;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (type==1){
                xlv.stopRefresh();
                Date date=new Date(System.currentTimeMillis());
                SimpleDateFormat format=new SimpleDateFormat("yyyy_MM_dd HH:mm:ss");
                String format1 = format.format(date);
                xlv.setRefreshTime(format1);
            }if (type==2){
                xlv.stopLoadMore();
            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.remen, container, false);
       xlv  = (XListView) v.findViewById(R.id.xlv);

        boolean result= NetTypeUtils.isConn(getActivity());
        if(result){
            //进行数据请求
            inittype();
            Toast.makeText(getActivity(),"有网络",Toast.LENGTH_SHORT).show();

        }else{
            NetTypeUtils.openNetSettingDg(getActivity());
            Toast.makeText(getActivity(),"无网络",Toast.LENGTH_SHORT).show();
        }
        xlv.setPullLoadEnable(true);
        xlv.setPullRefreshEnable(true);
        xlv.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                type=1;
                page=1;
                inittype();
            }
            @Override
            public void onLoadMore() {
                type=2;
                page++;
                inittype();
            }
        });
        return v;
    }
    public  void  inittype() {
        class MyTask extends AsyncTask<String, Void, String> {

            private String s = "";
            @Override
            protected String doInBackground(String... params) {

                try {
                    //1.创建URL
                    URL url = new URL(params[0]);
                    //2.打开连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //3.设置请求方法
                    connection.setRequestMethod("GET");//大写
                    connection.setConnectTimeout(2000);
                    connection.setReadTimeout(2000);
                    if (connection.getResponseCode() == 200) {
                        InputStream stream = connection.getInputStream();
                        s = StreamToString.streamToStr(stream, "utf-8");
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
                return s;
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Gson gson = new Gson();
                Resulte resulte = gson.fromJson(s, Resulte.class);

                if (type==1){
                    list.clear();
                    list.addAll(resulte.getResults());
                }else {
                    list.addAll(resulte.getResults());
                }
                xlv.setAdapter(new MyAdapter(getActivity(), list));
                handler.sendEmptyMessageDelayed(0,1000);
            }
        }
        new  MyTask().execute(url);
    }
}

MyAdapter

public class MyAdapter extends BaseAdapter {
    private DisplayImageOptions options;
    Context context;
    private List<Resulte.ResultsBean> list;
    int TYTLE_ONLY = 0;//只有文字的形式
    int IMAGE_LEFT = 1;//表示图片在左边,文字在右边

    public MyAdapter(Context context, List<Resulte.ResultsBean> 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)//设置图片显示的色彩模式
                .displayer(new RoundedBitmapDisplayer(20))//设置圆角图片
                .build();
    }

    @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) {
        List<String> pic = list.get(position).getImages();
        if (pic == null) {
            return TYTLE_ONLY;
        } else if (pic != null && pic.size() == 1) {//集合长度是1
            return IMAGE_LEFT;//返回图片类型){
        } else {
            return TYTLE_ONLY;
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int type = getItemViewType(position);
        if (type == IMAGE_LEFT) {
            ViewHolderi holderi;
            if (convertView == null) {
                holderi = new ViewHolderi();
                convertView = View.inflate(context, R.layout.item_img, null);
                holderi.img_tv = (TextView) convertView.findViewById(R.id.img_tv);
                holderi.img = (ImageView) convertView.findViewById(R.id.img);
                convertView.setTag(holderi);
            } else {
                holderi = (ViewHolderi) convertView.getTag();
            }
            holderi.img_tv.setText(list.get(position).getDesc());

            ImageLoader.getInstance().displayImage(list.get(position).getImages().get(0), holderi.img, options);
            return convertView;
        } else if (type == TYTLE_ONLY) {

            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(context, R.layout.item_tx, null);
                holder.tv = (TextView) convertView.findViewById(R.id.tv);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tv.setText(list.get(position).getDesc());
            return convertView;
        }
        return  convertView;
    }


    class   ViewHolder{
        TextView tv;
    }
   class   ViewHolderi{
        ImageView img;
        TextView img_tv;
    }
}

bean类自己复制封住在首页中有接口.
MyApplication

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        //sd卡上缓存目录-android指定的缓存路径 android/data/<package>/cache
        File cachefile=getExternalCacheDir();
        //自定义的缓存路径
//        File cachefile=new File(Environment.getExternalStorageDirectory().getPath()+"/abc/a");


        //进行框架初使化操作-全局配置
        ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this)
                .memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽
                .threadPoolSize(2)//线程池的数量
                .threadPriority(4)
                .memoryCacheSize(5*1024*1024)//设置内存缓存区大小
                .diskCacheSize(20*1024*1024)//设置sd卡缓存区大小
                .diskCache(new UnlimitedDiscCache(cachefile))//自定义磁盘缓存目录
                .writeDebugLogs()//打印日志内容
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理
                .build();

        ImageLoader.getInstance().init(configuration);
    }
}

猜你喜欢

转载自blog.csdn.net/aideat/article/details/78766844