为什么没有调用android ViewPager OnTouchListener

时间:2016-05-12 14:40:22

标签: java android android-viewpager ontouchlistener

为什么我的ViewPager OnTouchListener根本没有发射!!

以下是我的代码:

我使用ViewPager自动滑动照片,但是当我点击ViewPager时,我需要停止自动滑动,但问题是我的OnTouchListener没有&#39}总而言之。

JAVA

man_fragment.java

package com.techzone.yallaassouk;

/**
 * Created by Yazan on 4/26/2016.
 */
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.techzone.yallaassouk.Adapters.Brands_View_Adapter;
import com.techzone.yallaassouk.Adapters.Categories_View_Adapter;
import com.techzone.yallaassouk.Adapters.ImageSlideAdapter;
import com.techzone.yallaassouk.DataItems.Band;
import com.techzone.yallaassouk.DataItems.Brand;
import com.techzone.yallaassouk.DataItems.Category;
import com.techzone.yallaassouk.Utils.CirclePageIndicator;
import com.techzone.yallaassouk.Utils.PageIndicator;
import com.techzone.yallaassouk.Utils.CheckNetworkConnection;
import com.techzone.yallaassouk.json.GetJSONObject;
import com.techzone.yallaassouk.json.JsonReader;


import org.json.JSONObject;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;

public class man_fragment extends Fragment {

    public static final String ARG_ITEM_ID = "man_fragment";

    private static final long ANIM_VIEWPAGER_DELAY = 5000;
    private static final long ANIM_VIEWPAGER_DELAY_USER_VIEW = 10000;
    private static final int TabNo = 1;

    // UI References
    ViewPager BandsViewPager;
    PageIndicator mIndicator;
    RecyclerView brands_Rec_View;
    RecyclerView categories_Rec_View;

    //lists
    List<Band> bands;
    List<Brand> brands;
    List<Category> categories;

    //tasks
    RequestBandsTask bands_task;
    RequestBrandsTask brands_task;
    RequestCategoriesTask categories_task;

    AlertDialog alertDialog;
    boolean stopSliding = false;
    String message;

    //lists adapters
    Brands_View_Adapter brands_adapter;
    Categories_View_Adapter categories_adapter;

    //runnables and handlers
    private Runnable animateViewPager;
    private Handler handler;

    //urls
    String brandsurl = "http://yazanallahham-001-site1.ftempurl.com/Brands.svc/json/brands/"+TabNo;
    String categoriesurl = "http://yazanallahham-001-site1.ftempurl.com/categories.svc/json/categories/"+TabNo+"/0";
    String bandsurl = "http://yazanallahham-001-site1.ftempurl.com/bands.svc/json/bands/0";

    //activity
    FragmentActivity activity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.man_fragment, container, false);

        findViewById(rootView);

        mIndicator.setOnPageChangeListener(new PageChangeListener());
        BandsViewPager.setOnPageChangeListener(new PageChangeListener());
        BandsViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.getParent().requestDisallowInterceptTouchEvent(true);
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        stopSliding = true;
                        break;

                    case MotionEvent.ACTION_CANCEL:
                        break;

                    case MotionEvent.ACTION_UP:
                        // calls when touch release on ViewPager
                        if (bands != null && bands.size() != 0) {
                            stopSliding = false;
                            runnable(bands.size());
                            handler.postDelayed(animateViewPager,
                                    ANIM_VIEWPAGER_DELAY_USER_VIEW);
                        }
                        break;

                    case MotionEvent.ACTION_MOVE:
                        // calls when ViewPager touch
                        if (handler != null && stopSliding == false) {
                            stopSliding = true;
                            handler.removeCallbacks(animateViewPager);
                        }
                        break;
                }
                return false;
            }
        });

//        sendRequest();

        //init brands recyclerview
        brands_Rec_View.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));
        brands_Rec_View.addOnItemTouchListener(
                new RecyclerItemClickListener(this.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        categories_fragment nextFrag= new categories_fragment();
                        Bundle args = new Bundle();
                        Brand clickedBrand = (Brand)brands.get(position);
                        args.putInt("BrandId", clickedBrand.getId());
                        args.putInt("TabId", TabNo);
                        args.putString("BrandName", clickedBrand.getEnName());
                        nextFrag.setArguments(args);
                        getFragmentManager().beginTransaction()
                                .replace(R.id.main_content, nextFrag, categories_fragment.ARG_ITEM_ID)
                                .addToBackStack(categories_fragment.ARG_ITEM_ID)
                                .commit();
                    }
                })
        );

        //init categories recyclerview
        GridLayoutManager LLM =  new GridLayoutManager(activity, 2, LinearLayoutManager.VERTICAL, false){
            @Override
            public boolean canScrollVertically(){
                return false;
            }
        };
        categories_Rec_View.setLayoutManager(LLM);
        categories_Rec_View.addOnItemTouchListener(
                new RecyclerItemClickListener(this.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        //Log.d("categories","test click" + position);
                        Items_fragment nextFrag= new Items_fragment();
                        Bundle args = new Bundle();
                        Category clickedCategory = (Category)categories.get(position);
                        args.putInt("CategoryId", clickedCategory.getId());
                        args.putString("CategoryName", clickedCategory.getEnName());
                        args.putInt("BrandId", 0);
                        args.putInt("TabId", TabNo);
                        nextFrag.setArguments(args);
                        getFragmentManager().beginTransaction()
                                .replace(R.id.main_content, nextFrag, Items_fragment.ARG_ITEM_ID)
                                .addToBackStack(Items_fragment.ARG_ITEM_ID)
                                .commit();
                    }
                })
        );
        return rootView;
    }

    private void findViewById(View view) {
        BandsViewPager = (ViewPager) view.findViewById(R.id.man_view_pager);
        mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
        brands_Rec_View = (RecyclerView) view.findViewById(R.id.brands_RView);
        categories_Rec_View = (RecyclerView) view.findViewById(R.id.categories_RView);
    }

    public void runnable(final int size) {
        handler = new Handler();
        animateViewPager = new Runnable() {
            public void run() {
                if (!stopSliding) {
                    if (BandsViewPager.getCurrentItem() == size - 1) {
                        BandsViewPager.setCurrentItem(0);
                    } else {
                        BandsViewPager.setCurrentItem(
                                BandsViewPager.getCurrentItem() + 1, true);
                    }
                    handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
                }
            }
        };
    }


    @Override
    public void onResume() {
        if (bands == null) {
            sendRequest();
        } else {
            BandsViewPager.setAdapter(new ImageSlideAdapter(activity, bands,
                    man_fragment.this));
            mIndicator.setViewPager(BandsViewPager);
            runnable(bands.size());
            //Re-run callback
            handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
        }
        super.onResume();
    }


    @Override
    public void onPause() {
        if (bands_task != null)
            bands_task.cancel(true);
        if (handler != null) {
            //Remove callback
            handler.removeCallbacks(animateViewPager);
        }
        super.onPause();
    }

    private void sendRequest() {
        if (CheckNetworkConnection.isConnectionAvailable(activity)) {
            bands_task = new RequestBandsTask(activity);
            bands_task.execute(bandsurl);

            brands_task = new RequestBrandsTask(activity);
            brands_task.execute(brandsurl);

            categories_task = new RequestCategoriesTask(activity);
            categories_task.execute(categoriesurl);
        } else {
            message = getResources().getString(R.string.no_internet_connection);
            showAlertDialog(message, true);
        }
    }

    public void showAlertDialog(String message, final boolean finish) {
        alertDialog = new AlertDialog.Builder(activity).create();
        alertDialog.setMessage(message);
        alertDialog.setCancelable(false);

        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (finish)
                            activity.finish();
                    }
                });
        alertDialog.show();
    }

    private class PageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE) {
                if (bands != null) {
                }
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private class RequestBandsTask extends AsyncTask<String, Void, List<Band>> {
        private final WeakReference<Activity> activityWeakRef;
        Throwable error;

        public RequestBandsTask(Activity context) {
            this.activityWeakRef = new WeakReference<Activity>(context);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<Band> doInBackground(String... urls) {
            try {
                JSONObject jsonObject = getJsonObject(urls[0]);
                if (jsonObject != null) {
//                    JSONObject jsonData = jsonObject
//                            .getJSONObject(TagName.TAG_BRANDS);
//                    if (jsonObject != null) {
                        bands = JsonReader.getBands(jsonObject);

//                    } else {
//                        message = jsonObject.getString(TagName.TAG_BRANDS);
//                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bands;
        }

        /**
         * It returns jsonObject for the specified url.
         *
         * @param url
         * @return JSONObject
         */
        public JSONObject getJsonObject(String url) {
            JSONObject jsonObject = null;
            try {
                jsonObject = GetJSONObject.getJSONObject(url);
            } catch (Exception e) {
            }
            return jsonObject;
        }

        @Override
        protected void onPostExecute(List<Band> result) {
            super.onPostExecute(result);

            if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
                if (error != null && error instanceof IOException) {
                    message = getResources().getString(R.string.time_out);
                    showAlertDialog(message, true);
                } else if (error != null) {
                    message = getResources().getString(R.string.error_occured);
                    showAlertDialog(message, true);
                } else {
                    bands = result;
                    if (result != null) {
                        if (bands != null && bands.size() != 0) {
                            //for brands_adapter
                            BandsViewPager.setAdapter(new ImageSlideAdapter(
                                    activity, bands, man_fragment.this));

                            mIndicator.setViewPager(BandsViewPager);
                            runnable(bands.size());
                            handler.postDelayed(animateViewPager,
                                    ANIM_VIEWPAGER_DELAY);

                        } else {
                        }
                    } else {
                    }
                }
            }
        }
    }

    private class RequestBrandsTask extends AsyncTask<String, Void, List<Brand>> {
        private final WeakReference<Activity> activityWeakRef;
        Throwable error;

        public RequestBrandsTask(Activity context) {
            this.activityWeakRef = new WeakReference<Activity>(context);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<Brand> doInBackground(String... urls) {
            try {
                JSONObject jsonObject = getJsonObject(urls[0]);
                if (jsonObject != null) {
//                    JSONObject jsonData = jsonObject
//                            .getJSONObject(TagName.TAG_BRANDS);
//                    if (jsonObject != null) {
                    brands = JsonReader.getBrands(jsonObject);

//                    } else {
//                        message = jsonObject.getString(TagName.TAG_BRANDS);
//                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return brands;
        }

        /**
         * It returns jsonObject for the specified url.
         *
         * @param url
         * @return JSONObject
         */
        public JSONObject getJsonObject(String url) {
            JSONObject jsonObject = null;
            try {
                jsonObject = GetJSONObject.getJSONObject(url);
            } catch (Exception e) {
            }
            return jsonObject;
        }

        @Override
        protected void onPostExecute(List<Brand> result) {
            super.onPostExecute(result);

            if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
                if (error != null && error instanceof IOException) {
                    message = getResources().getString(R.string.time_out);
                    showAlertDialog(message, true);
                } else if (error != null) {
                    message = getResources().getString(R.string.error_occured);
                    showAlertDialog(message, true);
                } else {
                    brands = result;
                    if (result != null) {
                        if (brands != null && brands.size() != 0) {
                            //for brands_adapter
                            brands_adapter = new Brands_View_Adapter(brands);
                            brands_Rec_View.setAdapter(brands_adapter);// set adapter on recyclerview
                        } else {
                        }
                    } else {
                    }
                }
            }
        }
    }

    private class RequestCategoriesTask extends AsyncTask<String, Void, List<Category>> {
        private final WeakReference<Activity> activityWeakRef;
        Throwable error;

        public RequestCategoriesTask(Activity context) {
            this.activityWeakRef = new WeakReference<Activity>(context);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<Category> doInBackground(String... urls) {
            try {
                JSONObject jsonObject = getJsonObject(urls[0]);
                if (jsonObject != null) {
//                    JSONObject jsonData = jsonObject
//                            .getJSONObject(TagName.TAG_BRANDS);
//                    if (jsonObject != null) {
                    categories = JsonReader.getCategories(jsonObject);

//                    } else {
//                        message = jsonObject.getString(TagName.TAG_BRANDS);
//                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return categories;
        }

        /**
         * It returns jsonObject for the specified url.
         *
         * @param url
         * @return JSONObject
         */
        public JSONObject getJsonObject(String url) {
            JSONObject jsonObject = null;
            try {
                jsonObject = GetJSONObject.getJSONObject(url);
            } catch (Exception e) {
            }
            return jsonObject;
        }

        @Override
        protected void onPostExecute(List<Category> result) {
            super.onPostExecute(result);

            if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
                if (error != null && error instanceof IOException) {
                    message = getResources().getString(R.string.time_out);
                    showAlertDialog(message, true);
                } else if (error != null) {
                    message = getResources().getString(R.string.error_occured);
                    showAlertDialog(message, true);
                } else {
                    categories = result;
                    if (result != null) {
                        if (categories != null && categories.size() != 0) {
                            //for brands_adapter

                            categories_adapter = new Categories_View_Adapter(categories);
                            categories_Rec_View.setAdapter(categories_adapter);// set adapter on recyclerview
                            categories_Rec_View.getLayoutParams().height = (188*(categories_adapter.getItemCount()+1)+328);
                        } else {
                        }
                    } else {
                    }
                }
            }
        }
    }
}

查看寻呼机适配器

ImageSlideAdapter.java

package com.techzone.yallaassouk.Adapters;

/**
 * Created by Yazan on 5/1/2016.
 */

import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.ViewParent;
import android.widget.ImageView;

import java.util.Collections;
import java.util.LinkedList;
        import java.util.List;

        import android.app.Activity;
        import android.graphics.Bitmap;

        import android.support.v4.app.Fragment;
        import android.support.v4.app.FragmentActivity;
        import android.support.v4.app.FragmentTransaction;
        import android.support.v4.view.PagerAdapter;
        import android.util.Log;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.view.ViewGroup;
        import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.techzone.yallaassouk.DataItems.Band;
import com.techzone.yallaassouk.R;

import com.techzone.yallaassouk.TouchImageView;
import com.techzone.yallaassouk.fragment.ProductDetailFragment;
import com.techzone.yallaassouk.man_fragment;
        import com.nostra13.universalimageloader.core.DisplayImageOptions;
        import com.nostra13.universalimageloader.core.ImageLoader;
        import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
        import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
        import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class ImageSlideAdapter extends PagerAdapter {
    ImageLoader imageLoader = ImageLoader.getInstance();
    DisplayImageOptions options;
    private ImageLoadingListener imageListener;
    FragmentActivity activity;
    List<Band> bands;
    Fragment homeFragment;
    public ImageSlideAdapter(FragmentActivity activity, List<Band> bands,
                             Fragment homeFragment) {
        this.activity = activity;
        this.homeFragment = homeFragment;
        this.bands = bands;
        options = new DisplayImageOptions.Builder()
                .showImageOnFail(R.drawable.a1)
                .showStubImage(R.drawable.a2)
                .showImageForEmptyUri(R.drawable.a3).cacheInMemory()
                .cacheOnDisc().build();

        imageListener = new ImageDisplayListener();
    }

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

    @Override
    public View instantiateItem(ViewGroup container, final int position) {
        LayoutInflater inflater = (LayoutInflater) activity
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.vp_image, container, false);

        ImageView mImageView = (ImageView) view
                .findViewById(R.id.image_display);

        imageLoader.displayImage(
                ((Band) bands.get(position)).getImageURL(), mImageView,
                options, imageListener);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

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

    private static class ImageDisplayListener extends
            SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }
}

抱歉没有格式化。我是新来的

1 个答案:

答案 0 :(得分:1)

我发现导致'ViewPager'不会触发'OnTouchListener'的原因

在布局 XML 文件中:

<com.techzone.yallaassouk.ExtendedViewPager
    android:id="@+id/man_view_pager"
    android:layout_width="fill_parent"
    android:layout_height="137dp" />

<com.techzone.yallaassouk.Utils.CirclePageIndicator
    android:id="@+id/indicator"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="130dp"/>

问题是'CirclePageIndicator'的'paddingTop'被设置为'130dp',覆盖'ViewPager',它接收触摸事件而不是'ViewPager'本身。

谢谢。