1. 程式人生 > >viewPager + recycleView 實現左右滑動

viewPager + recycleView 實現左右滑動


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="280dp">

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="240dp"
        android:id="@+id/viewpage">

    </android.support.v4.view.ViewPager>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_gravity="bottom"
        android:id="@+id/oval_layout"
        >

    </LinearLayout>

</LinearLayout>

下面為recycleAdapter的程式碼

public class RecycleViewAdapter extends RecyclerView.Adapter {
    private List<Model> list;//model類中有兩個屬性以及其get和set方法
    private int page;
    private int row;
    public RecycleViewAdapter(List<Model> list,int page,int row) {
        this.list=list;
        this.page=page;
        this.row=row;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.data, parent, false);
        MyHodler hodler = new MyHodler(view);
        return hodler;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyHodler myHodler=(MyHodler)holder;
        myHodler.imageView.setImageResource(list.get(position+(page-1)*10).getId());
        myHodler.textView.setText(list.get(position+(page-1)*10).getName());

    }

    @Override
    public int getItemCount() {
        return list.size()>page*row*5?row*5:(list.size()-(page-1)*row*5);
    }

    class MyHodler extends RecyclerView.ViewHolder{
        TextView textView;
        ImageView imageView;
        public MyHodler(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewById(R.id.name);
            imageView = (ImageView) itemView.findViewById(R.id.image);
        }
    }
}

接下來是ViewPagerAdapter的程式碼
public class ViewPageAdapter extends PagerAdapter {
    private List<View> list;//這個是儲存了RecycleView

    public ViewPageAdapter(List<View> list) {
        this.list=list;
    }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        container.removeView(list.get(position));
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
      /*  for (View view : list) {
            ViewGroup parent=(ViewGroup)view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
        }*/
        //解決The specified child already has a parent. You must call removeView() on the child's parent first.
        ViewGroup parent=(ViewGroup)list.get(position).getParent();
        if (parent != null) {
            parent.removeView(list.get(position));
        }
        container.addView(list.get(position));
        return list.get(position);
    }
}
 
最後是mainavtivity
public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;

    private int prePosition=0;
    private LinearLayout linearLayout;
    private ViewPager viewPager;
    private  int pagecount;
    private ArrayList<Model> list=new ArrayList<>();
    private ArrayList<View> listsView=new ArrayList<>();
    private RecycleViewAdapter recycleViewAdapter;
    private String[] titles = {"美食", "電影", "酒店住宿", "休閒娛樂", "外賣", "自助餐", "KTV", "機票/火車票", "周邊遊", "美甲美睫",
            "火鍋", "生日蛋糕", "甜品飲品", "水上樂園", "汽車服務", "美髮", "麗人", "景點", "足療按摩", "運動健身", "健身", "超市", "買菜",
            "今日新單", "小吃快餐", "面膜", "洗浴/汗蒸", "母嬰親子", "生活服務", "婚紗攝影", "學習培訓", "家裝", "結婚", "全部分配"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_page);

        viewPager = (ViewPager) findViewById(R.id.viewpage);
        /*View view= LayoutInflater.from(this).inflate(R.layout.recycle_view, viewPager, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycle);
        recyclerView.setLayoutManager(new GridLayoutManager(this,5));*/
        linearLayout = (LinearLayout) findViewById(R.id.oval_layout);
        initdata();
         pagecount=(int)(titles.length/10)+1;
        Log.d("test", pagecount+":pagecount");
        //根據介面卡的不同新增不同的recycleview
        //*********並且為每個頁面都inflate出例項

        for (int i=1;i<=pagecount;i++){
            View view= LayoutInflater.from(this).inflate(R.layout.recycle_view, viewPager, false);
            recyclerView = (RecyclerView) view.findViewById(R.id.recycle);
            recyclerView.setLayoutManager(new GridLayoutManager(this,5));

            recycleViewAdapter = new RecycleViewAdapter(list, i, 2);
            recyclerView.setAdapter(recycleViewAdapter);
            listsView.add(recyclerView);
        }
        //如果同時新增兩個名字為view1的則滑動的時候會報錯
        //The specified child already has a parent. You must call removeView() on the child's parent first.
        /*View view = LayoutInflater.from(this).inflate(R.layout.oval_view, viewPager, false);
        View view1 = LayoutInflater.from(this).inflate(R.layout.content_main, viewPager, false);
        View view2 = LayoutInflater.from(this).inflate(R.layout.text, viewPager, false);
        View view3 = LayoutInflater.from(this).inflate(R.layout.text, viewPager, false);
        listsView.add(view3);
        listsView.add(view);
        listsView.add(view2);
        listsView.add(view1);*/

        viewPager.setAdapter(new ViewPageAdapter(listsView));
        viewPager.setPageTransformer(true,new MyPageTransformor());
        setOval();
        mhandle.sendEmptyMessageDelayed(1, 1000);
    }
    public void initdata(){
        //動態獲取資源ID,第一個引數是資源名,第二個引數是資源型別例如drawable,string等,第三個引數包名
        for (int i=0;i<titles.length;i++) {
            list.add(new Model(titles[i], getResources().getIdentifier("ic_category_" + i, "mipmap", getPackageName())));
        }
    }
    public void setOval(){//這個是設定滑動頁面時下面的小圓會跟著滑動

        //將oval_view新增到linearlayout中
        for (int i=0;i<pagecount;i++) {

            linearLayout.addView(LayoutInflater.from(this).inflate(R.layout.oval_view,null));
        }
        //好多個錯誤
        //1當子view有parent的時候用addview將view新增到一個容器中會有錯
        //解決辦法將整個子view所在的layout新增到另一個layout中
        linearLayout.getChildAt(0).findViewById(R.id.oval_no_select).setBackgroundResource(R.drawable.oval_select);
        //2當滑動頁面的時候沒有出現小圓點變現
        //解決辦法:找到小圓點layout。通過layout找到小圓點,直接改變小圓點的顏色
        //之前是linearLayout.getChildAt(0).setBackgroundResource(R.drawable.oval_select);
        //改變的只是layout的顏色
        //3,頁面滑動的時候顏色沒有改變
        //將要改變顏色的程式碼放入onPageSelected中
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {


                Log.d("test", positionOffset + "positionOffset");
            }

            @Override
            public void onPageSelected(int position) {
                linearLayout.getChildAt(position).findViewById(R.id.oval_no_select).
                        setBackgroundResource(R.drawable.oval_select);
                linearLayout.getChildAt(prePosition).findViewById(R.id.oval_no_select).
                        setBackgroundResource(R.drawable.oval_1);
                prePosition=position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        flag=false;
                        break;
                    case ViewPager.SCROLL_STATE_IDLE:
                        flag=true;
                        break;
                }
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();

    }
    private Handler mhandle=new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    int current=(position)%pagecount;

                    viewPager.setCurrentItem(current,true);
                    position++;
                    break;
                case 2:
                    position++;
                    break;

            }
        }
    };
    class MyThread extends Thread{
        @Override
        public void run() {
            super.run();
            while (true) {
                Message message=new Message();
                if (flag)
                    message.what=1;
                else
                    message.what=2;
                mhandle.sendMessage(message);
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {

                }
            }
        }
    }
    boolean   flag=true;
    private int position=0;


}