当我水平滑动到另一个选项卡时,swiperefreshlayout onrefresh()方法有效。

时间:2015-10-04 21:26:27

标签: android android-fragments android-viewpager swiperefreshlayout

我无法实现刷卡刷新。我正在使用 Viewpager 和一个标签布局,其中包含4个标签。我在我的一个标签片段活动中实现了 swiperefreshlayout 并实现了onRefresh()方法来加载新数据,但每当我水平滑动到另一个标签时,会自动调用onRefresh()方法并启动再次加载数据和应用程序因此崩溃。 我试图设置 setOnTouchListener(),但它也不起作用。如果你们帮我解决问题,那将是非常有帮助的。

Personal_class.java

package com.example.ebad.testingapp;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;

public class Personal_Class extends Fragment implements java.io.Serializable {

    TextView f_n, s_n, em_n, cl_n, mo_n, reg_n, enroll_n, names, enrolles;
    String url;

    View.OnClickListener mOnClickListener;
    private SwipeRefreshLayout swipeContainer;

    HashMap<String, String> hashMap;

    String filename = "PersonalData";
    static String urladder = "PersonalInfo.aspx";
    File file;
    FileOutputStream outputStream;
    FileInputStream inputStream;

    public static ViewPager viewPager;
    public static TabLayout tabLayout;

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

        url = Data.URL;

        url += urladder;
        hashMap = Data.map;


        final View rootviewe = inflater.inflate(R.layout.personal_layout, container, false);

        swipeContainer = (SwipeRefreshLayout) rootviewe.findViewById(R.id.swipe_refresh_layout);

        View x = inflater.inflate(R.layout.tab_layout, null);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);


        s_n = (TextView) rootviewe.findViewById(R.id.Y_Name);
        em_n = (TextView) rootviewe.findViewById(R.id.email);
        mo_n = (TextView) rootviewe.findViewById(R.id.mobile);
        reg_n = (TextView) rootviewe.findViewById(R.id.reg);
        enroll_n = (TextView) rootviewe.findViewById(R.id.enroll);
        cl_n = (TextView) rootviewe.findViewById(R.id.classe);


       mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //finish();
                //System.exit(0);
            }
        };


        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Your code to refresh the list here.
                // Make sure you call swipeContainer.setRefreshing(false)
                // once the network request has completed successfully.
                if (isOnline()) {
                    swipeContainer.setRefreshing(false);
                    Intent intent = new Intent(getActivity(), Testing_Activity.class);
                    startActivity(intent);


                } else {
                    swipeContainer.setRefreshing(false);

                    Snackbar snackbar = Snackbar
                            .make(getActivity().findViewById(android.R.id.content), "No Network Connection.", Snackbar.LENGTH_LONG)
                            .setAction("ok", mOnClickListener);
                    snackbar.setActionTextColor(Color.parseColor("#2196f3"));

                    View snackbarView = snackbar.getView();
                    snackbarView.setBackgroundColor(Color.DKGRAY);

                    TextView textViews = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_action);
                    textViews.setTextSize(12);

                    TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
                    textView.setTextColor(Color.WHITE);
                    textView.setTextSize(14);
                    snackbar.show();
                }
                swipeContainer.setRefreshing(false);
            }

        });


        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                swipeContainer.setEnabled(false);
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        swipeContainer.setEnabled(true);
                        break;
                }
                return false;
            }
        });





        swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        if (!isOnline()) {
            Personal_Data personal_data = new Personal_Data("", "", "", "", "", "", "");
            try {

                File filew = new File(getContext().getCacheDir(), filename);
                inputStream = new FileInputStream(filew);

                ObjectInputStream input = new ObjectInputStream(inputStream);
                personal_data = (Personal_Data) input.readObject();

                s_n.setText(personal_data.getSon());
                em_n.setText(personal_data.getEmail());
                cl_n.setText(personal_data.getClas());
                mo_n.setText(personal_data.getMobi());
                reg_n.setText(personal_data.getRegs());
                enroll_n.setText(personal_data.getEnrollment());

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            new personaldatagetter().execute();
        }
        return rootviewe;

    }

    private class personaldatagetter extends AsyncTask<Void, Void, Void> {
        String son, Enrollmente, em, mobi, clas, regs, Email_new;


        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Void doInBackground(Void... params) {

            try {
                Document doce = Jsoup.connect(url)
                        .cookies(hashMap)
                        .get();

                son = doce.select("span[id=ctl00_Body_NAME]").html();
                Enrollmente = doce.select("span[id=ctl00_Body_ENROLLMENT]").html();
                mobi = doce.select("span[id=ctl00_Body_MOBILE]").html();
                em = doce.select("span[id=ctl00_Body_EMAIL]").html();
                regs = doce.select("span[id=ctl00_Body_REGISTRATION]").html();
                clas = doce.select("span[id=ctl00_Body_CLASS]").html();
                Email_new = doce.select("span[id=ctl00_Body_lblStudent_Email]").html();

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPreExecute();

            s_n.setText(son);
            em_n.setText(em);
            cl_n.setText(clas);
            mo_n.setText(mobi);
            reg_n.setText(regs);
            enroll_n.setText(Enrollmente);

            Personal_Data p = new Personal_Data(son, em, Enrollmente, mobi, clas, regs, Email_new);

            try {

                File files = new File(getContext().getCacheDir(), filename);
                outputStream = new FileOutputStream(files);
                ObjectOutputStream outputStream1 = new ObjectOutputStream(outputStream);
                outputStream1.writeObject(p);
                outputStream1.flush();
                outputStream1.close();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        //should check null because in air plan mode it will be null
        return (netInfo != null && netInfo.isConnected());
    }
}

personal_layout.xml

<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/white"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sikandar.myapplication.MainActivity3">



    <LinearLayout
        android:id="@+id/linearLayout4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/linearLayout5"
        android:layout_alignLeft="@+id/linearLayout5"
        android:layout_alignStart="@+id/linearLayout5"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Enrollment"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/enroll"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="01-134132-180"
                android:textSize="17sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Class"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/classe"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="60dp"
                android:layout_marginTop="10dp"
                android:text="BSCS 4B"
                android:textSize="17sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Email"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="60sp"
                android:layout_marginTop="10dp"

                android:textSize="17sp" />

        </LinearLayout>

    </LinearLayout>

    <View
        android:id="@+id/SplitLine_hor2"
        android:layout_width="300dp"
        android:layout_height="5dp"
        android:layout_alignBottom="@+id/linearLayout9"
        android:layout_alignLeft="@+id/SplitLine_hor1"
        android:layout_alignStart="@+id/SplitLine_hor1"
        android:layout_marginBottom="48dp"
        android:background="@drawable/line" />

    <View
        android:id="@+id/SplitLine_hor1"
        android:layout_width="300dp"
        android:layout_height="5dp"
        android:layout_above="@+id/linearLayout4"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="25dp"
        android:background="@drawable/line" />

    <View
        android:id="@+id/linearLayout9"
        android:layout_width="2dp"
        android:layout_height="500dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="@drawable/line" />

    <View
        android:id="@+id/linearLayout10"
        android:layout_width="2dp"
        android:layout_height="500dp"
        android:layout_alignParentLeft="false"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="false"
        android:background="@drawable/line" />

    <LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="164dp"
        android:layout_marginTop="10dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView8"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Contact"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/mobile"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="42dp"
                android:text="03115117085"
                android:textSize="17sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView10"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Registration"
                android:textSize="17sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/reg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="11dp"
                android:layout_marginTop="10dp"
                android:text="1234"
                android:textSize="17sp" />
        </LinearLayout>

    </LinearLayout>

    <TextView
        android:id="@+id/Y_Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/SplitLine_hor1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="44dp"
        android:text="Sikandar Iqbal"
        android:textColor="#ff000000"
        android:textSize="20sp"
        android:textStyle="bold" />

</RelativeLayout>

</android.support.v4.widget.SwipeRefreshLayout>

TabFragment.java

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TabFragment extends Fragment {

    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 4;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /**
         *Inflate tab_layout and setup Views.
         */
        View x = inflater.inflate(R.layout.tab_layout, null);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
        viewPager.setOffscreenPageLimit(3);


        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter {

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

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return new Personal_Class();
                case 1:
                    return new Attetandance_Class();
                case 2:
                    return new Exam_Seating_Class();
                case 3:
                    return new Result_Class();
            }
            return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position) {
                case 0:
                    return "Personal";
                case 1:
                    return "Attendance";
                case 2:
                    return "Exam";
                case 3:
                    return "Result";
            }
            return null;
        }
    }
}

tablayout.xml

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


    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:background="?attr/colorPrimary"
        app:tabIndicatorColor="@color/white"
        app:tabSelectedTextColor="@color/white"

        app:tabTextColor="@color/md_grey_500_25"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.design.widget.TabLayout>

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

    </android.support.v4.view.ViewPager>



</LinearLayout>

0 个答案:

没有答案