接口回調

Mytask:

package com.example.com.aa.Util;

import android.os.AsyncTask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by 聯想 on 2018/1/12.
 */

public class Mytask extends AsyncTask<String,Void,String>{

    //申請接口類對象
    private  Icallbacks icallbacks;

    //將無參構造設置成私有的,是他在外部不能調用
    private Mytask(){}

//定義有參構造
    public Mytask(Icallbacks icallbacks){
        this.icallbacks=icallbacks;
    }
    @Override
    protected String doInBackground(String... strings) {
        String str="";
        try {
            URL url = new URL(strings[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(5000);
            urlConnection.setConnectTimeout(5000);
            if (urlConnection.getResponseCode()==200){
                InputStream inputStream = urlConnection.getInputStream();
                //調用工具類中的靜態方法
                str=statemtostring.statemstr(inputStream,"utf-8");
            }else if(urlConnection.getResponseCode()==301 ||urlConnection.getResponseCode()==302 ){
                //拿到重定向的地址
                String newUrl=urlConnection.getHeaderField("location");

                URL u=new URL(newUrl);
                HttpURLConnection connection1=(HttpURLConnection) u.openConnection();
                connection1.setRequestMethod("GET");
                connection1.setReadTimeout(5000);
                connection1.setConnectTimeout(5000);

                if(connection1.getResponseCode()==200){
                    InputStream inputStream=connection1.getInputStream();
                    //調用工具類中的靜態方法
                    str=statemtostring.statemstr(inputStream,"utf-8");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return str;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //解析,封裝到bean,更新ui組件
        icallbacks.updateUiByjson(s);
    }

    //定義一個接口
    public interface Icallbacks{
        //根據回傳的jsoon串,解析並更新頁面組件
        void updateUiByjson(String jsonstr);
    }
}

statemtostring:

package com.example.com.aa.Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * Created by 聯想 on 2018/1/12.
 */

public class statemtostring {
    public static  String statemstr(InputStream inputStream,String charSet){
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charSet));
            String con;
            while((con=br.readLine())!=null){
                builder.append(con);
            }
            br.close();
            return builder.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
mainActivity中;

package com.example.com.aa;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.example.com.aa.Adapter.MyAdapter;
import com.example.com.aa.Bean.RequestdataBean;
import com.example.com.aa.Util.Mytask;
import com.google.gson.Gson;

import java.util.List;

/**
 * Created by 聯想 on 2018/1/11.
 */

public class Contentfragment extends Fragment {

    private View view;
    private TextView tview;
    private ListView lv;
    private String data;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.connectfragment,container,false);
        tview = view.findViewById(R.id.tview);
        lv = view.findViewById(R.id.lv);
        Bundle arguments = getArguments();
        data = arguments.getString("data");

        getDatas();


        return view;
    }


    public void getDatas() {
        Mytask mytask = new Mytask(new Mytask.Icallbacks() {
            @Override
            public void updateUiByjson(String jsonstr) {
                Gson gson = new Gson();
                RequestdataBean requestdataBean = gson.fromJson(jsonstr, RequestdataBean.class);
                List<RequestdataBean.ResultBean.DataBean> data = requestdataBean.getResult().getData();
                MyAdapter myAdapter = new MyAdapter(getActivity(),data);
lv.setAdapter(myAdapter);

            }
        });
        mytask.execute("http://v.juhe.cn/toutiao/index?type="+data+"&key=444da40ec8ee43818073d7131c2ffa8f");
    }
}
碎片:

package com.example.com.aa;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class Fragment01 extends Fragment {
    private TextView dian;
    private View view;
    private ViewPager vp;
    private List<String> list;
    private TabLayout tabout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_fragment01, container, false);
        dian = view.findViewById(R.id.dian);
        vp = view.findViewById(R.id.vp);

        tabout = view.findViewById(R.id.tabout);
        dian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), secondsou.class);
                startActivity(intent);
            }
        });
        listData();
        vp.setAdapter(new MyAdapter(getChildFragmentManager()));
        tabout.setupWithViewPager(vp);

        return view;
    }

    private void listData() {
        list = new ArrayList<>();
        list.add("推薦");
        list.add("新時代");
        list.add("熱點");
        list.add("北京");
        list.add("視頻");
        list.add("圖片");
        list.add("娛樂");
        list.add("問答");
        list.add("科技");
        list.add("汽車");
        list.add("財經");
        list.add("軍事");
        list.add("體育");
        list.add("段子");
        list.add("國際");
        list.add("趣圖");
        list.add("健康");
        list.add("房產");
    }

    class MyAdapter extends FragmentPagerAdapter {

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

        @Override
        public CharSequence getPageTitle(int position) {
            return list.get(position);
        }

        @Override
        public Fragment getItem(int position) {
           Contentfragment contentfragment = new Contentfragment();
             Bundle bundle = new Bundle();
            if (list.get(position).equals("推薦")){
                bundle.putString("data", "top");
            }else if(list.get(position).equals("新時代")){
                bundle.putString("data","guoji");
            }
            //傳值
            contentfragment.setArguments(bundle);
            return contentfragment;
        }

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



}
佈局文件:
<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.com.aa.Fragment01">

    <include layout="@layout/include"></include>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabout"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="73dp"
        app:tabGravity="center"
        app:tabIndicatorColor="#fff"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="#f00"
        app:tabTextColor="@color/colorPrimary"></android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tabout"></android.support.v4.view.ViewPager>
</RelativeLayout>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章