ListView+Fragment+ViewPager配合,实现今日头条的效果

  • Post author:
  • Post category:其他


首先需要第三方控件PagerSlidingTabStrip-master的使用。

ListView放入Fragment,之后再放入ViewPager中。

准备工作:三方控件PagerSlidingTabStrip-master的导入,下载PagerSlidingTabStrip-master,点击File中New中的Import Module,找到PagerSlidingTabStrip-master存放的位置,点击PagerSlidingTabStrip-master下的builder,根据自己的build,修改PagerSlidingTabStrip-master的build。

步骤:1.建立需要传入的新闻类,命名为News。

2.建立Activity,命名为FragmentPager,建立Fragment命名为pagerFragment。

3.建立ListView,以及ListView适配器命名MyListViewAdapter 将ListView放入Fragment中。

4.建立MyfragmentAdapter适配器,将Fragment与ViewPager。

效果图之一:

这里写图片描述

这里写图片描述

          以下为代码及具体实现过程
         首先是:建立News,将属性写出,简单的get/set方法,构造参数,要实现一个页面多种布局,我们需要多个构造参数,这里使用了两种,记得我们需要构造一个空的构造函数,以防报错。
public class News  implements Parcelable{
    private String title;
    private String pubDate;
    private String from;
    private int img;
    private int img1;
    private int img2;
    private int img3;

    public News(int img3, String title, String pubDate, String from, int img1, int img2) {
        this.img3 = img3;
        this.title = title;
        this.pubDate = pubDate;
        this.from = from;
        this.img1 = img1;
        this.img2 = img2;
    }

    public int getImg3() {
        return img3;
    }

    public void setImg3(int img3) {
        this.img3 = img3;
    }

    public int getImg2() {
        return img2;
    }

    public void setImg2(int img2) {
        this.img2 = img2;
    }

    public int getImg1() {
        return img1;
    }

    public void setImg1(int img1) {
        this.img1 = img1;
    }

    public News() {

    }
    public News(String title, String pubDate, String from, int img) {
        this.title = title;
        this.pubDate = pubDate;
        this.from = from;
        this.img = img;
    }

    protected News(Parcel in) {
        title = in.readString();
        pubDate = in.readString();
        from = in.readString();
        img = in.readInt();
    }

    public static final Creator<News> CREATOR = new Creator<News>() {
        @Override
        public News createFromParcel(Parcel in) {
            return new News(in);
        }

        @Override
        public News[] newArray(int size) {
            return new News[size];
        }
    };

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPubDate() {
        return pubDate;
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }

    public int getImg() {
        return img;
    }

    public void setImg(int img) {
        this.img = img;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(title);
        dest.writeString(pubDate);
        dest.writeString(from);
        dest.writeInt(img);
    }
}

FragmentPager

package com.edu.jereh.android7;

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

import com.astuetz.PagerSlidingTabStrip;
import com.edu.jereh.android7.adapter.MyfragmentAdapter;
import com.edu.jereh.android7.fragment.pagerFragment;

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

public class FragmentPager extends AppCompatActivity {
    private ViewPager vp;
    private PagerSlidingTabStrip pst;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_pager);
        getSupportActionBar().hide();
        vp=(ViewPager)findViewById(R.id.vp);
        pst=(PagerSlidingTabStrip)findViewById(R.id.pst);
        List<Fragment> list=new ArrayList<>();
        List<String> titles=new  ArrayList<>();
        titles.add("推荐");
        titles.add("热点");
        titles.add("烟台");
        titles.add("视频");
        titles.add("订阅");
        titles.add("体育");
        titles.add("娱乐");
        titles.add("奥运");
        titles.add("财经");
        titles.add("国际");

        for(int i=1;i<10;i++){
            Fragment fragment=new pagerFragment();
            Bundle bundle=new Bundle();
            bundle.putInt("arg",i);
            fragment.setArguments(bundle);
            list.add(fragment);
        }
        MyfragmentAdapter ma=new MyfragmentAdapter(
                getSupportFragmentManager(),list,titles);
        vp.setAdapter(ma);
        //ViewPage自带滑动
       // vp.setPageTransformer(true,new ZoomOutPageTransformer());
        vp.setPageTransformer(true,new DepthPageTransformer());
       pst.setIndicatorColor(getResources().getColor(R.color.colorPrimary));//边框颜色
        pst.setIndicatorHeight(5);
        //pst.setShouldExpand(true);//平分,当它小的时候让它铺满整个屏幕
        pst.setTextColor(getResources().getColor(R.color.colorAccent));//字的颜色


        pst.setViewPager(vp);
    }

}

pagerFragment

public class pagerFragment extends Fragment {


    public pagerFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_pager, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //TextView tv=(TextView)getView().findViewById(R.id.tv);
       int []a= new int[]{R.mipmap.a,R.mipmap.b,R.mipmap.c,R.mipmap.d,R.mipmap.e,R.mipmap.f,R.mipmap.g,R.mipmap.h,R.mipmap.i,R.mipmap.j,R.mipmap.k,R.mipmap.l,R.mipmap.m,R.mipmap.n};
        ListView lv=(ListView)getView().findViewById(R.id.lv);
        final List<News> list=new ArrayList<>();
        MyListViewAdapter ma=new MyListViewAdapter(list,getActivity());
        lv.setAdapter(ma);
        final Bundle bundle=getArguments();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 // News news=list.get(position);
                //弹出点击新闻的Title传值
                News news=list.get(position);
                Intent intent=new Intent(getActivity(), IntentActivity.class);
                intent.putExtra("obj",news);
                //intent.putExtra("obj", news);
                Bundle bundle1=new Bundle();
                bundle1.putString("arg1", "今天是七月七");
                intent.putExtra("bundle",bundle1);
                startActivity(intent);

            }
        });
        if(bundle!=null){
            int arg=bundle.getInt("arg");
           // lv.setText("我是Fragment"+arg);

            switch (arg){
                case 1:
//                    for(int i=0;i<a.length;i++){
//                        list.add(new News("体育新闻"+i,"今天","新浪网",a[i]));
//                    }
                    list.add(new News("体育新闻","今天","新浪网",R.mipmap.lh2));
                    list.add(new News(R.mipmap.lh2,"体育新闻","今天","新浪网",R.mipmap.lh2,R.mipmap.lh2));
                    ma.notifyDataSetChanged();
                    break;
                case 2:
                    for(int i=0;i<20;i++){
                        list.add(new News("娱乐新闻"+i,"今天","新浪网",R.mipmap.lh2));
                    }
                    ma.notifyDataSetChanged();

                    break;
                case 3:
                    for(int i=0;i<20;i++){
                        list.add(new News("财经新闻"+i,"今天","新浪网",R.mipmap.lh3));
                    }
                    ma.notifyDataSetChanged();

                    break;
                case 4:
                    for(int i=0;i<20;i++){
                        list.add(new News("军事新闻"+i,"今天","新浪网",R.mipmap.lh4));
                    }
                    ma.notifyDataSetChanged();
                    break;
            }
        }
    }
}

MyfragmentAdapter继承于FragmentPagerAdapter

public class MyfragmentAdapter extends FragmentPagerAdapter {
    private List<Fragment> list;
    private List<String> titles;
    public MyfragmentAdapter(FragmentManager fm, List<Fragment> list,List<String> titles) {
        super(fm);
        this.list=list;
        this.titles=titles;

    }

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

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

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

    }
}

MyListViewAdapter继承于BaseAdapter

public class MyListViewAdapter extends BaseAdapter {
    private List<News> list;
    private List<String> titles;
    private Context context;
    private  final int TYPE1=0;//声明常量大写
    private  final int TYPE2=1 ;

    public MyListViewAdapter(List<News> list, Context context) {
        this.context = context;
        this.list = list;
    }

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

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

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

    public int getViewTypeCount() {
        return 2;
    }
    @Override
    public int getItemViewType(int position) {
//        News news=list.get(position);
        if(list.get(position).getImg1()==0){
            return TYPE1;
        }else{
            return TYPE2;
        }

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        int type=getItemViewType(position);
        if(convertView == null){
            vh=new ViewHolder();
            if(type==0){
                convertView= LayoutInflater.from(context).inflate(R.layout.list_layout,null);
                vh.img=(ImageView)convertView.findViewById(R.id.img);
                vh.title=(TextView)convertView.findViewById(R.id.title);
                vh.pubDate=(TextView)convertView.findViewById(R.id.pubDate);
                vh.from=(TextView)convertView.findViewById(R.id.from);
                convertView.setTag(vh);
            }else {
                convertView= LayoutInflater.from(context).inflate(R.layout.list_layout2,null);
                vh.title=(TextView)convertView.findViewById(R.id.title);
                vh.pubDate=(TextView)convertView.findViewById(R.id.time);
                vh.from=(TextView)convertView.findViewById(R.id.from);
                vh.img1=(ImageView)convertView.findViewById(R.id.iv1);
                vh.img2=(ImageView)convertView.findViewById(R.id.iv2);
                vh.img3=(ImageView)convertView.findViewById(R.id.iv3);
                convertView.setTag(vh);
            }

        }else{
            vh=(ViewHolder)convertView.getTag();
        }

        News news=list.get(position);
        if(type==0){
            vh.img.setImageResource(news.getImg());
            vh.title.setText(news.getTitle());
            vh.pubDate.setText(news.getPubDate());
            vh.from.setText(news.getFrom());
        }else{
            vh.title.setText(news.getTitle());
            vh.pubDate.setText(news.getPubDate());
            vh.from.setText(news.getFrom());
            vh.img1.setImageResource(news.getImg1());
            vh.img2.setImageResource(news.getImg2());
            vh.img3.setImageResource(news.getImg3());

        }
        return convertView;
    }
    private  class ViewHolder{
        ImageView img;
        TextView title;
        TextView pubDate;
        TextView from;
        ImageView img1;
        ImageView img2;
        ImageView img3;
    }
}

MyTabHostAdapter继承于FragmentPagerAdapter

public class MyTabHostAdapter extends FragmentPagerAdapter {
    private List<Fragment> list;
    public MyTabHostAdapter(FragmentManager fm, List<Fragment> list) {
        super(fm);
        this.list= list;
    }
    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }
    @Override
    public int getCount() {
        return list.size();
    }
}

FragmentTab继承于Fragment

public class FragmentTab extends Fragment {

public FragmentTab() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_fragment_tab, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    TextView tv=(TextView)getView().findViewById(R.id.tv);
    Log.d("====","89");
    Bundle bundle=getArguments();
    if(bundle!=null){
        int arg = bundle.getInt("arg");
        tv.setText("我是Fragment"+(arg+1));
    }
}

}

IntentActivity

public class IntentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent);
        TextView tv=(TextView)findViewById(R.id.tv);
        Intent intent=getIntent();
       // News news= (News) intent.getSerializableExtra("obj");
        News news=  intent.getParcelableExtra("obj");
        Bundle bundle=intent.getBundleExtra("bundle");
        String arg=bundle.getString("arg1");
        //String str=news.getTitle();
        StringBuilder sbld=new StringBuilder();
        sbld.append(arg);
        sbld.append("\n");
        sbld.append(news.getTitle());
        sbld.append(news.getPubDate());
        sbld.append(news.getFrom());
        //sbld.append(news.getImg().toString());
        tv.setText(sbld.toString());
    }
}

TabHostFragment继承于Fragment

public class TabHostFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public TabHostFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TabHostFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TabHostFragment newInstance(String param1, String param2) {
        TabHostFragment fragment = new TabHostFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_tab_host, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

最后是效果图展示:

这里写图片描述

这里写图片描述



版权声明:本文为woainijinying原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。