1. 程式人生 > >ListView+Fragment+ViewPager配合,實現今日頭條的效果

ListView+Fragment+ViewPager配合,實現今日頭條的效果

首先需要第三方控制元件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);
    }
}

最後是效果圖展示:
這裡寫圖片描述
這裡寫圖片描述