Viewpager和Fragment问题

时间:2016-06-21 12:08:13

标签: android android-layout android-fragments android-viewpager

使用案例Fragment上有一个Activity,它在 Splash 之后启动。我的FragmentViewPager组成,在ViewPager TabLayout上显示了一些值。如果我第一次运行它,一切正常;但如果我从设备上的后台删除应用程序并再次运行它,则ViewPager选项卡上的文本详细信息不会显示。

代码

splash 之后调用

Fragment并由ViewPager -

组成
public class SlidingTab extends Fragment {
    private static final String TAG = "TabLayout";
    private static String POSITION = "POSITION";
    private Context context;
    private AppCompatActivity activity;
    private FragmentActivity fragmentContext;
    // private Toolbar toolbar;
    private TextView badge;
    private ViewPager viewPager;
    private TabLayout slidingTab;
    private BroadcastReceiver mMyBroadcastReceiver;
    private SearchView searchview;
    // private LinearLayout bellLayout , accountInfoLayout;
    private Boolean flag = false;
    android.widget.PopupWindow changeStatusPopUp;
    Point point;
    // private SearchView searchview;
    private Toolbar toolbar;
    private LinearLayout maplistview, listView;
    private PreferenceforApp myprefs;
    private PageAdapter adapter;
    private Bundle bundle;

    public SlidingTab() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.sliding_tab, container, false);

        initialise(v);
        initialiseListeners();
        bundle = getArguments();
        return v;
    }

    private void initialiseListeners() {

    }

    private void initialise(View v) {
        context = getActivity();
        myprefs = new PreferenceforApp(context);
        activity = (AppCompatActivity) getActivity();
        viewPager = (ViewPager) v.findViewById(R.id.view_pager);
        viewPager.setOffscreenPageLimit(2);
        adapter = new PageAdapter(getChildFragmentManager(), context);
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(viewPager.getWindowToken(), 0);
                // adapter.set_current_position(1,2,3);
                // adapter.notifyDataSetChanged();

                if (bundle != null && bundle.size() != 0) {
                    if ((!bundle.getString("viewpager").equalsIgnoreCase("submit")) &&
                            (!bundle.getString("viewpager").equalsIgnoreCase("inProgress"))) {
                        slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
                        slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");
                        slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");
                    }
                    bundle.clear();
                } else {
                    slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
                    slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");
                    slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        slidingTab = (TabLayout) v.findViewById(R.id.sliding_tabs);
        badge = (TextView) v.findViewById(R.id.badge);
        badge.setVisibility(View.GONE);
        final RelativeLayout bellLayout = (RelativeLayout) v.findViewById(R.id.bell_linearlayout1);
        final RelativeLayout accountInfoLayout = (RelativeLayout) v.findViewById(R.id.account_linearlayout1);
        if (myprefs.getCounter() != 0) {
            badge.setVisibility(View.VISIBLE);
        }

        toolbar = (Toolbar) v.findViewById(R.id.toolbar1);
        maplistview = (LinearLayout) v.findViewById(R.id.maplist);
        listView = (LinearLayout) v.findViewById(R.id.list_linearlayout);
        activity = (AppCompatActivity) getActivity();
        searchview = (SearchView) v.findViewById(R.id.searchView);
        searchview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchview.setIconified(false);
            }
        });

        LinearLayout logout_Layout = (LinearLayout) layout.findViewById(R.id.logoutlayout);
        logout_Layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popup.dismiss();
                FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                myprefs.setUserState(LoginActivity
                        .setLoginState(Constant.userStateLoggedOut));
                Log.i("logged out", myprefs.getUserState());
                myprefs.setIsLogIn(false);

                Intent myIntent = new Intent(getActivity(), LoginActivity.class);
                myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);

                startActivity(myIntent);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (activity.getSupportActionBar() != null) {
            if (activity.getSupportActionBar().isShowing()) {
                activity.getSupportActionBar().hide();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (activity.getSupportActionBar() != null) {
            if (!activity.getSupportActionBar().isShowing()) {
                activity.getSupportActionBar().show();
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (outState != null) {
            outState.putInt(POSITION, slidingTab.getSelectedTabPosition());
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstaceState) {
        super.onActivityCreated(savedInstaceState);
        Log.d(TAG, "onActivityCreated Called");
    }

    @Override
    public void onResume() {
        super.onResume();
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        if (bundle != null) {
            if (bundle.containsKey("viewpager")) {
                if (bundle.getString("viewpager").equalsIgnoreCase("submit")) {
                    viewPager.setCurrentItem(2, false);
                } else if (bundle.getString("viewpager").equalsIgnoreCase("inProgress")) {
                    viewPager.setCurrentItem(1, false);
                }
            }
        }

        mMyBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // Here you can refresh your listview or other UI
                badge.setVisibility(View.VISIBLE);
            }
        };

        try {
            LocalBroadcastManager.getInstance(context).registerReceiver(mMyBroadcastReceiver, 
                    new IntentFilter("com.parse.push.intent.RECEIVE"));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            // Toast.makeText(getActivity(), "GPS is Enabled on your device", Toast.LENGTH_SHORT).show();
        } else {
            Utils.showGPSDisabledAlertToUser(getContext());
        }
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        LocalBroadcastManager.getInstance(context).unregisterReceiver(mMyBroadcastReceiver);
    }

}

在上面的代码中,这些是用于设置ViewPager标签文本的行。首先调用它,但是从背景中删除应用程序并重新启动后,在选择其中一个选项卡之前,不会显示任何数据。

            slidingTab.getTabAt(0).setText("New ("+ SingleTon.getInstance().getNewjob()+")");
            slidingTab.getTabAt(1).setText("In Progress ("+ SingleTon.getInstance().getInprogressjob()+")");
            slidingTab.getTabAt(2).setText("Completed ("+ SingleTon.getInstance().getCompletedjob()+")");

        }
    });
}

SlidingTab.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/frame_main"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@android:color/white"
              android:orientation="vertical"
              tools:context="com.RareMediaCompany.BDTrial.SlidingTab">

    <include
        android:id="@+id/toolbar1"
        layout="@layout/toolbar_job"/>

    <com.RareMediaCompany.BDTrial.Utils.CustomTabLayout
        android:id="@+id/sliding_tabs"
        style="@style/CustomTabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#eeeeee"
        app:tabIndicatorColor="#f39220"
        app:tabIndicatorHeight="3dp"
        app:tabMaxWidth="0dp"
        app:tabMode="fixed"
        app:tabPaddingEnd="0dp"
        app:tabPaddingStart="0dp"
        app:tabSelectedTextColor="#808080"
        app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"/>

    <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="8dp"
        android:background="@android:color/white"
        android:orientation="horizontal"
        android:weightSum="1">

        <android.support.v7.widget.SearchView
            android:id="@+id/searchView"
            style="@style/CitySearchView"
            android:layout_width="300dp"
            android:layout_height="45dp"
            android:layout_gravity="center"
            android:layout_marginEnd="5dp"
            android:layout_marginLeft="5dp"
            android:layout_weight="1"
            android:background="@drawable/searchview"
            android:clickable="true"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:orientation="horizontal"
            android:weightSum="1">

            <LinearLayout
                android:id="@+id/list_linearlayout"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:layout_gravity="center"
                android:layout_weight="0.5"
                android:background="#f39220">
                <!--android:background="#75aadb">-->
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="2dp"
                    android:layout_weight="0.3"
                    android:src="@drawable/listicon"/>

            </LinearLayout>

            <LinearLayout
                android:id="@+id/maplist"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:layout_gravity="center"
                android:layout_weight="0.5"
                android:background="#75aadb">

                <ImageView
                    android:layout_width="20dp"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="3dp"
                    android:layout_marginTop="2dp"
                    android:layout_weight="0.3"
                    android:src="@drawable/map_icon_1"/>

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>
    <!--android:layout_width="320dp"-->
    <!--android:layout_height="wrap_content"-->
    <!--android:layout_marginLeft="10dp"-->
    <!--android:layout_marginTop="10dp"-->
    <!--android:id="@+id/searchview"/>-->

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@android:color/white"/>

</LinearLayout>

MainActivity.java(包含片段的活动)

    private static MainActivity mainActivityRunningInstance;

    public static MainActivity getInstance() {
        return mainActivityRunningInstance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mainActivityRunningInstance = this;

        Fabric.with(this, new Crashlytics());

        overridePendingTransition(R.anim.grow_from_middle, R.anim.shrink_to_middle);
        setContentView(R.layout.activity_main);
        contentFragment = NavigationDrawerFragment.newInstance(R.drawable.content_music);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerLayout.setScrimColor(Color.TRANSPARENT);
        linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.closeDrawers();
            }
        });
        myPref = new PreferenceforApp(MainActivity.this);
        fragmentManager = getSupportFragmentManager();

        setActionBar(title);
        // createMenuList();
        viewAnimator = new ViewAnimator<>(this, list, contentFragment, drawerLayout, this);

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.anim.glide_fragment_horizontal_in, R.anim.glide_fragment_horizontal_out);
        ft.replace(R.id.content_frame1, new SlidingTab(), "recycler");
        ft.addToBackStack("recycler");
        ft.commit();
    }

图片

在应用程序首次启动时:

enter image description here

从后台删除后重新运行:

enter image description here

  

有人可以指出错误是什么或建议采用不同的方法。

ViewPager代码

public class PageAdapter extends FragmentStatePagerAdapter {
    private static final String TAG = "PageAdapter";
    public int newjob, inprogressjob, completedjob;
    final int PAGE_COUNT = 3;
    Fragment fragment;
    private String tabTitles[] = new String[]{"New", "In Progress", "Completed"};
    private Context context;
    HashMap<Integer,Fragment> map = new HashMap<>();
    public PageAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.context = context;
    }


    @Override
    public Fragment getItem(int position) {
        Log.d(TAG, "New Instance Created :" + position);
        switch (position) {
            case 0:
                fragment = new JobFragment();
                map.put(position,fragment);
                return fragment;

            case 1:
                fragment=new InProgressJobFragment();
                map.put(position,fragment);
                return fragment;
            case 2:
                fragment = new CompletedJobFragment();
                map.put(position,fragment);
                return fragment;
        }
        return null;
    }


    public Fragment getFragment(int key) {
        return map.get(key);
    }

    public void set_current_position(int newjob, int inprogress, int completedjob) {
       this.newjob = newjob;
        this.inprogressjob = inprogress;
        this.completedjob = completedjob;

        notifyDataSetChanged();
    }

//    @Override
//    public CharSequence getPageTitle(int position) {
//        return tabTitles[position];
//    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0: return "New" + " (" + SingleTon.getInstance().getNewjob() + ")";
            case 1: return "In Progress" + " (" + SingleTon.getInstance().getInprogressjob() + ")";
            case 2: return "Completed" + " (" + SingleTon.getInstance().getCompletedjob() + ")";
        }
        return "";
    }
    @Override
    public int getCount() {
        return PAGE_COUNT;
    }

    private String getFragmentTag(int viewPagerId, int fragmentPosition)
    {
        return "android:switcher:" + viewPagerId + ":" + fragmentPosition;
    }
}

1 个答案:

答案 0 :(得分:2)

我认为问题是由于主线程

引起的

使用以下代码 希望它能解决你的问题

slidingTab.postDelayed(new Runnable() {
           @Override
           public void run() {
               slidingTab.setupWithViewPager(viewPager);

               slidingTab.getTabAt(0).setText("New ("+ SingleTon.getInstance().getNewjob()+")");
               slidingTab.getTabAt(1).setText("In Progress ("+ SingleTon.getInstance().getInprogressjob()+")");
               slidingTab.getTabAt(2).setText("Completed ("+ SingleTon.getInstance().getCompletedjob()+")");

           }
       },2500);
   }