TabLayout 和ViewPager和Fragment的多页面滑动

来源:互联网 发布:师洋淘宝店铺生意好吗 编辑:程序博客网 时间:2024/06/06 16:34


先导依赖

布局
<LinearLayout 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"    >    <android.support.design.widget.TabLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/tab"        app:tabGravity="center"        app:tabIndicatorColor="#ff0"        android:background="#000"        app:tabSelectedTextColor="#ff0000"        app:tabTextColor="#aaa"        app:tabMode="scrollable"        app:tabIndicatorHeight="4dp"        />    <android.support.v4.view.ViewPager        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/pager"        /></LinearLayout>


布局
<com.jwenfeng.library.pulltorefresh.PullToRefreshLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/mpull"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    >    <ListView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/list"        ></ListView></com.jwenfeng.library.pulltorefresh.PullToRefreshLayout>

布局
<LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/name"        />    <ImageView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/img"        /></LinearLayout>



主页面


public class MainActivity extends AppCompatActivity {    private TabLayout tab;    private ViewPager pa;    private List<String> list=new ArrayList<String>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //查找控件        tab = (TabLayout) findViewById(R.id.tab);        pa = (ViewPager) findViewById(R.id.pager);        //tab的标题        list.add("头条");        list.add("社会");        list.add("国内");        list.add("国际");        list.add("娱乐");        list.add("体育");        list.add("军事");        list.add("科技");        list.add("财经");        list.add("时尚");        //tablayout和viewpager关联        tab.setupWithViewPager(pa);        //设置viewpager适配器        pa.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {            //重写这个方法,将设置每个Tab的标题            @Override            public CharSequence getPageTitle(int position) {                return list.get(position);            }            @Override            public Fragment getItem(int position) {                //一般我们在这个位置对比一下标题是什么,,,然后返回对应的fragment                //初始化fragment  对应position有多少,fragment有多少                NewFragment newFragment = new NewFragment();                Bundle bundle = new Bundle();                if (list.get(position).equals("头条")){                    bundle.putString("name","top");                }else if (list.get(position).equals("社会")){                    bundle.putString("name","shehui");                }else if (list.get(position).equals("国内")){                    bundle.putString("name","guonei");                }else if (list.get(position).equals("国际")){                    bundle.putString("name","guoji");                }else if (list.get(position).equals("娱乐")){                    bundle.putString("name","yule");                }else if (list.get(position).equals("体育")){                    bundle.putString("name","tiyu");                }else if (list.get(position).equals("军事")){                    bundle.putString("name","junshi");                }else if (list.get(position).equals("科技")){                    bundle.putString("name","keji");                }else if (list.get(position).equals("财经")){                    bundle.putString("name","caijing");                }else if (list.get(position).equals("时尚")){                    bundle.putString("name","shishang");                }                //给fragment 加bundle 数据                //activity与fragment 1.getset,2.接口回调,3.setArguments ,getAraguments                newFragment.setArguments(bundle);                return newFragment;            }            @Override            public int getCount() {                return list.size();            }        });    }}


______________________________________________________________

NewFragment类

public class NewFragment extends Fragment {    private ListView list;    private PullToRefreshLayout mpull;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        //找到布局文件        View v = View.inflate(getActivity(), R.layout.listview, null);        //ListView控件        list = (ListView)v.findViewById(R.id.list);        mpull = v.findViewById(R.id.mpull);        mpull.setRefreshListener(new BaseRefreshListener() {            @Override            public void refresh() {                new Handler().postDelayed(new Runnable() {                    @Override                    public void run() {                        // 结束刷新                        mpull.finishRefresh();                    }                }, 2000);            }            @Override            public void loadMore() {                new Handler().postDelayed(new Runnable() {                    @Override                    public void run() {                        // 结束加载更多                        mpull.finishLoadMore();                    }                }, 2000);            }        });        return v;    }    @Override    public void onActivityCreated(@Nullable Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        Bundle bundle = getArguments();        //接收传递过来的值        String string = bundle.getString("name", "福利");            //调用解析方法            Jiexi(string);    }    //解析方法    private void Jiexi(final String string) {        //使用异步        new AsyncTask<String,Integer,String>(){            @Override            protected String doInBackground(String... strings) {                String str="";                try {                    URL url = new URL("http://v.juhe.cn/toutiao/index?type="+string+"&key=8c6e9ca2058eaffcc04bcc4c0f5920c6");                    HttpURLConnection conne= (HttpURLConnection) url.openConnection();                    conne.setConnectTimeout(5000);                    conne.setReadTimeout(5000);                    int responseCode = conne.getResponseCode();                    if (responseCode==200){                        InputStream in = conne.getInputStream();                        byte[] by=new byte[1024];                        int len=0;                        while ((len=in.read(by))!=-1){                            str+=new String(by,0,len);                        }                    }                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }                return str;            }            @Override            protected void onPostExecute(String s) {                Log.d("zzz","qqqqqqqqqqqqqqqqqq"+s);                //Gson解析                Gson gson = new Gson();                User user = gson.fromJson(s, User.class);                List<User.ResultBean.DataBean> data = user.getResult().getData();                //listview适配器                Myadpader myadpader = new Myadpader(data, getActivity());                list.setAdapter(myadpader);                super.onPostExecute(s);            }        }.execute();    }}

______________________________________________________________


适配器

public class Myadpader extends BaseAdapter {   private List<User.ResultBean.DataBean> data;   private Context context;    public Myadpader(List<User.ResultBean.DataBean> data, Context context) {        this.data = data;        this.context = context;    }    @Override    public int getCount() {        return data.size();    }    @Override    public Object getItem(int i) {        return null;    }    @Override    public long getItemId(int i) {        return 0;    }    @Override    public View getView(int i, View view, ViewGroup viewGroup) {        Hondera hondera=null;        if (view==null){            hondera = new Hondera();            view=  View.inflate(context,R.layout.ziti,null);            hondera.name=view.findViewById(R.id.name);            hondera.img= view.findViewById(R.id.img);            view.setTag(hondera);        }else{            hondera = (Hondera) view.getTag();        }        hondera.name.setText(data.get(i).getTitle());                ImageLoader.getInstance().displayImage(data.get(i).getThumbnail_pic_s(),hondera.img);        return view;    }    class Hondera{        TextView name;        ImageView img;    }}


获取图片

public class App extends Application {    @Override    public void onCreate() {        DisplayImageOptions options = new DisplayImageOptions.Builder()                //设置图片在下载期间显示的图片                .showImageOnLoading(R.mipmap.ic_launcher)                .displayer(new FadeInBitmapDisplayer(2000)).cacheOnDisk(true)                //设置下载的图片是否缓存在内存中                .cacheInMemory(true).build();        ImageLoaderConfiguration configs = new ImageLoaderConfiguration.Builder(                this).defaultDisplayImageOptions(options).threadPoolSize(5)                .build();        ImageLoader.getInstance().init(configs);        super.onCreate();    }}

效果




















阅读全文
1 0
原创粉丝点击