tablayout+fragment

本文介绍了一个使用Android Support库中的TabLayout和ViewPager组件实现多标签页面切换的应用案例。通过创建自定义适配器和Fragment,实现了数据的异步加载,并展示了如何设置TabLayout与ViewPager的联动效果。

MainActivity

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

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

public class MainActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private List<String> list = new ArrayList<>();
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = (TabLayout) findViewById(R.id.my_tab);
        viewPager = (ViewPager) findViewById(R.id.my_viewpager);
        inittab();
    }
    public void inittab(){
        List<Fragment> fragments=new ArrayList<>();
        fragments.add(new Fragment01());
        fragments.add(new Fragment01());
        fragments.add(new Fragment01());
        fragments.add(new Fragment01());
        fragments.add(new Fragment01());
        fragments.add(new Fragment01());
        fragments.add(new Fragment01());
        fragments.add(new Fragment01());
        fragments.add(new Fragment01());
        fragments.add(new Fragment01());
        viewPager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(),fragments));
        for (int i=0;i<fragments.size();i++){
            tabLayout.addTab(tabLayout.newTab());
        }
        //tablayout与viewpager关联
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.getTabAt(0).setText("热点");
        tabLayout.getTabAt(1).setText("热点2");
        tabLayout.getTabAt(2).setText("热点3");
        tabLayout.getTabAt(3).setText("热点4");
        tabLayout.getTabAt(4).setText("热点5");
        tabLayout.getTabAt(5).setText("热点6");
        tabLayout.getTabAt(6).setText("热点7");
        tabLayout.getTabAt(7).setText("热点8");
        tabLayout.getTabAt(8).setText("热点9");
        tabLayout.getTabAt(9).setText("热点10");


        /*//为tablayout设置ttitle
        for (int i = 0; i < 10; i++) {
            list.add("热" + i);
            tabLayout.addTab(tabLayout.newTab().setText(list.get(i)));
        }*/
    }
}
Fragment01

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.Toast;

import com.google.gson.Gson;
import com.limxing.xlistview.view.XListView;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

/**
 * 
 */

public class Fragment01 extends Fragment implements XListView.IXListViewListener{
    private List<bean.ResultBean.DataBean> list;
    private XListView xListView;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment01,container,false);
        xListView=view.findViewById(R.id.my_xlistview);
       // getData("http://apis.juhe.cn/cook/query.php","0","10");
        //getData("http://apis.juhe.cn/cook/query.php",index+"",10+"");
        getData();
        xListView.setPullLoadEnable(true);
        xListView.setPullRefreshEnable(true);
        xListView.setXListViewListener(this);
        return view;
    }

    /*@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // getData();
    }*/

    public void getData(){
        new AsyncTask<String, Void, String>() {
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if(s!=null){
                    Gson gson=new Gson();
                    bean beans=gson.fromJson(s,bean.class);
                    list=beans.getResult().getData();
                    xListView.setAdapter(new MyXlistviewAdapter(list,getActivity()));
                }
            }
            @Override
            protected String doInBackground(String... strings) {

                try {
                    String path=strings[0];
                    URL url=new URL(path);
                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    OutputStream os=connection.getOutputStream();
                    os.write("key=1e9834f5ac3a7000a9b13af1040403ae&menu=红烧肉&rn=10".getBytes());
                    //os.write(("key=1e9834f5ac3a7000a9b13af1040403ae&menu=红烧肉&pn="+pn+"&rn="+rn+"").getBytes());
                    os.flush();
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    int code=connection.getResponseCode();
                    if(code==HttpURLConnection.HTTP_OK){
                        InputStream is=connection.getInputStream();
                        ByteArrayOutputStream baos=new ByteArrayOutputStream();
                        int len=0;
                        byte[] buffer=new byte[1024];
                        while ((len=is.read(buffer))!=-1){
                            baos.write(buffer,0,len);
                        }
                        is.close();
                        baos.close();
                        return baos.toString();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute("http://apis.juhe.cn/cook/query.php");
    }


    //下拉刷新
    @Override
    public void onRefresh() {
        getData();
        xListView.stopRefresh(true);
    }

    //上拉加载
    @Override
    public void onLoadMore() {

        getData();

        xListView.stopLoadMore();
    }}
MyFragmentAdaptter

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

import java.util.List;

/**
 * 
 */

public class MyFragmentAdapter extends FragmentPagerAdapter {
    private List<Fragment> list;

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

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

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

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

}
MyXlistView

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;

/**
 * 
 */

public class MyXlistviewAdapter extends BaseAdapter {
    private List<bean.ResultBean.DataBean> list;
    private Context context;

    public MyXlistviewAdapter(List<bean.ResultBean.DataBean> list, Context context) {
        this.list = list;
        this.context = context;
    }

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

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

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder;
        if(view==null){
            holder=new ViewHolder();
            view=View.inflate(context,R.layout.item01,null);
            holder.myContent=view.findViewById(R.id.myContent);
            holder.myIcon=view.findViewById(R.id.myIcon);
            view.setTag(holder);
        }else{
            holder= (ViewHolder) view.getTag();
        }
        holder.myContent.setText(list.get(i).getTitle());
        Glide.with(context).load(list.get(i).getSteps().get(0).getImg()).animate(R.anim.item_alpha_in).into(holder.myIcon);
        return view;
    }
    class ViewHolder{
        TextView myContent;
        ImageView myIcon;
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.yuekaodemo01.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/my_tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"
        ></android.support.design.widget.TabLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/my_viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ></android.support.v4.view.ViewPager>

</LinearLayout>
fragment01.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <com.limxing.xlistview.view.XListView
        android:id="@+id/my_xlistview"
        android:divider="@null"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.limxing.xlistview.view.XListView>

</LinearLayout>
item01

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/myContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="3333333"
        />
    <ImageView
        android:id="@+id/myIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        />

</LinearLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值