关闭

TabLayout 和ViewPager和Fragment的多页面滑动(主要实现一个水平的布局用来展示Tabs加上ViewPager实现联动效果)

标签: TabLayout ViewpageFragment
107人阅读 评论(0) 收藏 举报


主要实现一个类似于头条最上面的水平的布局,可以拉动如:


      然后ViewPager主要负责实现展示LisyView条目,   代码如下 一步步开始:




首先导入依赖:    


compile 'com.android.support:design:26.0.0-alpha1'



接下来就是布局:


           

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="daylx0911.day0913tablayoutviewpager.MainActivity">


    <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"
                                         //改变整个TabLayout的颜色
        android:background="#000"
                                         //改变选中字体的颜色
        app:tabSelectedTextColor="#ff0000"
                                          //改变未选中字体的颜色
        app:tabTextColor="#aaa"
                                          //默认是fixed 固定的 标签很多时候会被挤压 不能滑动
                                          //scrollable 可以滑动的
        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>

====================================================================

MainActivity代码如下:


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();
            }
        });



    }
}

=========================================================================================

Fragment  类:

public class NewFragment extends Fragment {

    private ListView list;

    @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);

        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();
        //接收传递过来的值
        String string = bundle.getString("name", "top");
        //调用解析方法
        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=597b4f9dcb50e051fd725a9ec54d6653");
                    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) {
                //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();

    }

}

最后实现的效果:
                     这样写的好处是不需要写多个Fragment就可以实现多个不同的数据变化,只要滑动上面的Tab控件就可以变化数据
            省的写好多继承Fragment的类
     


1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1429次
    • 积分:160
    • 等级:
    • 排名:千里之外
    • 原创:0篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档