从另一个碎片回来时碎片消失了

时间:2016-09-08 21:16:27

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

我有一个包含3个片段的viewpager来制作可滑动的小部件。当我第一次加载应用程序时,它们正确显示,所有点击事件都按预期工作。与单击每个OnClick后按下后退按钮相同,将我发送回登录页面,并按预期显示viewpager / fragments。我的问题是,当我按下菜单按钮并返回登录页面时,我的查看寻呼机消失了。

在设置适配器时我确实尝试使用getChildFragmentManager()但是它可以正常运行但是我的onClick事件不再起作用了,因为我没有查看id *******。

我还尝试将适配器放在onResume();中,根本没有运气。

与viewpager一起,我的viewpagerindicator不是为homewidget工作,而是为carousel工作。不确定这是代码还是布局。但是我设置它与旋转木马相同,但在运行时仍然没有在屏幕上看到它。

Landingpagenotlogged

public class LandingPageFragmentLoggedOut extends LandingPageFragment {

    private static final String TAG = LandingPageFragmentLoggedOut.class.getSimpleName();
    private ViewPager viewPager;
    private RelativeLayout myStoreTab;
    private Button signIn;
    private final static Fragment instance = new LandingPageFragmentLoggedOut();
    LoggedOutWidgetAdapter mAdapter;
    ViewPager mPager;
    public static final int ITEMS = 3;


    static public Fragment getInstance() {
        return instance;
    }


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

        getActivity().startService(new Intent(getActivity().getApplicationContext(),
                WeeklyAdService.class));

        setShoppingListFocusChangeListener();
        setSignInBtnClickListener();
        super.setViewPagerMotionListeners(viewPager);
        setMenuTouchListener();
        setTabClickListener();
        return view;
    }


    @Override
    protected void inflateFragmentView(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.landingpage_not_logged_in, container,
                false);

        RelativeLayout thisLayout = (RelativeLayout) view
                .findViewById(R.id.landingpage_logged_out_parent_layout);
        TileBackground.fixBackgroundRepeat(thisLayout);
        imgArch = view.findViewById(R.id.frag_tab);

    }

    private void setSignInBtnClickListener() {
        signIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, String> params = new HashMap<>();

                Intent intent = new Intent(getActivity(), SignInActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(
                        R.anim.enter_in_from_bottom, R.anim.anim_static);

                params.put("Module", "Home");
                FlurryAgent.logEvent(FlurryConstants.GOTO_SIGN_IN, params);
            }
        });
    }


    private void setTabClickListener() {
        myStoreTab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tabSelection = 1;
                tabSelectionListener.onTabSelectionListener(tabSelection);
                toggleStoreTabIndicator(1);

            }
        });
    }

    @Override
    @SuppressLint("WrongViewCast")
    protected void setUIreferences() {
        viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
        overlay = view.findViewById(R.id.landingpage_screenOverlay);
        indicator = (LinePageIndicator) view.findViewById(R.id.image_slider_indicator);
        this.signIn = (Button) view.findViewById(R.id.landingpg_sign_in_btn);
        shoppingListBtn = (ImageView) view.findViewById(R.id.icnlistoptions);
        myStoreTab = (RelativeLayout) view.findViewById(R.id.frag_tab);
        menuButton = (Button) view.findViewById(R.id.imgBanner_list);
        logoButton = (ImageView) view.findViewById(R.id.headerLogo);
        addShoppingListItemWidget = (EditText) view.findViewById(R.id.editAddItemNotLoggedIn);
        addShoppingListItemWidget.setOnKeyListener(null);
        addedItemConfirmation = view.findViewById(R.id.addedItemConfirmation);
        imgScanner = (ImageView) view.findViewById(R.id.imgScannerNotLoggedIn);
        toggleScannerVisibility(true);
        itemAddedText = (TextView) view.findViewById(R.id.item_added_text);
        weeklyAdImg = (ImageView) view.findViewById(R.id.weeklyad_img);
        defaultWelcomeMsg = (ImageView) view.findViewById(R.id.landing_page_default_img);
        setWeeklyAdThumbNail();
        if(imgUrl!=null)
        Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
        else
            Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
        //setWeeklyAdOnClickListener();
        setWeeklyAdClickListener();
        couponsGrid = view.findViewById(R.id.coupons_grid);
        couponsPlaceholderImg = (ImageView) view.findViewById(R.id.feat_coupons);

        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
            itemAddedText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        }


        imgScanner.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                PermissionHandler.openCamera(getActivity());
            }
        });

        mShoppingListAdd = (RelativeLayout) view.findViewById(R.id.shoppinglis_shortcut);
        mShoppingListAdd.setVisibility(View.GONE);

        mAdapter = new LoggedOutWidgetAdapter(getFragmentManager());
        mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
        mPager.setAdapter(mAdapter);
        LinePageIndicator mLoggedOutWidgetIndicator = (LinePageIndicator)view.findViewById(R.id.homewidgetLoggedOutIndicator);
        mLoggedOutWidgetIndicator.setViewPager(mPager);
    }

    // MSM - 214
    private void setWeeklyAdThumbNail() {
        try {
            if (LocalDb.getStoreId() != LocalDb.DEFAULT_VAL) {
                if (weeklyAdBundle != null && !weeklyAdBundle.isEmpty()) {

                    //MSM - 155
                    if (!Utils.isStringNull(weeklyAdBundle.getString("WeeklyAdThumbnail"))) {
                        Log.e("BANNER ID SET: ", weeklyAdBundle.getString("WeeklyAdThumbnail"));
                        imgUrl = weeklyAdBundle.getString("WeeklyAdThumbnail");
                    }
                    else
                        imgUrl = weeklyAdBundle.getString("0FirstThumbnail");
                }
            }

            if (urls == null || !urls.contains(imgUrl)) {
                Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
            }
            else
            Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);

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

    @Override
    protected void sendRequest() {
        if (CheckNetworkConnection.isConnectionAvailable(activity)) {
            jsonParser = new CarouselJSONParser(this);
            jsonParser.execute();
        } else {
            setDefaultOfflineImage();
            weeklyAdImg.setImageResource(R.drawable.img_ad_default);

            // TODO Set OFFLINE message here
        }
    }

    @Override
    public void setCarouselData(ArrayList<CarouselImageData> imageDatas) {
        Log.v(TAG, "Set Carousel Data hit");
        if (imageDatas != null) {
            this.advertisements = imageDatas;
            runnable(advertisements.size());
            handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
            viewPager
                    .setAdapter(new ImageSliderAdapter(activity, imageDatas, this, weeklyAdBundle));
            indicator.setViewPager(viewPager);


            if (isFirstTimeLaunched) {
                fadeInWelcomMsg();
                Log.v(TAG, "first time launched, welcome message initaited");

            } else {
                viewPager.setVisibility(View.VISIBLE);
                indicator.setVisibility(View.VISIBLE);
                Log.v(TAG, "Returning user, viewpager set visible");

            }
        } else {
            setDefaultOfflineImage();
        }
    }


    @Override
    public void onResume() {
        if (LocalDb.isLoggedIn()) {
            Fragment fragment = new LandingPageFragment();
            launchNavigationItemFragment(fragment);
        }

        getActivity().startService(new Intent(getActivity().getApplicationContext(),
                WeeklyAdService.class));
        if (viewPager == null) {
            viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
        }
        mAdapter = new LoggedOutWidgetAdapter(getChildFragmentManager());
        super.onResume();

        if (newItemIsAdded) {
            onShoppingListResult();
        }
    //    addShoppingListItemWidget.clearFocus();

    }

    @Override
    void runnable(final int size) {
        handler = new Handler();
        animateViewPager = new Runnable() {
            @Override
            public void run() {
                if (!pageIsSliding) {
                    if (viewPager.getCurrentItem() == size - 1) {
                        viewPager.setCurrentItem(0);
                    } else {
                        viewPager.setCurrentItem(
                                viewPager.getCurrentItem() + 1, true);
                    }
                    handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
                }
            }
        };
    }

    @Override
    void toggleStoreTabIndicator(int tab) {
        if (storeTabIsClosed) {
            storeTabIsClosed = false;
            imgArch.setBackgroundResource(R.drawable.img_single_arch_my_store);
        } else {
            storeTabIsClosed = true;
            imgArch.setBackgroundResource(R.drawable.img_arch);
        }

    }

    @Override
    protected void setFontsOnTextViews(View view) {

    }

    @Override
    protected void setTabClickListeners() {

    }

    @Override
    public void setViewPagerMotionListeners(ViewPager vPager) {

    }

    public class LoggedOutWidgetAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return ProductLocatorHomeWidgetFragment.init(position);

                case 1:
                    return ProductScanHomeWidgetFragment.init(position);

                case 2:
                    return MyShoppingListHomeWidgetFragment.init(position);

                default:
                    return null;

            }
        }

        @Override
        public int getCount() {
            return ITEMS;
        }
    }
}

绑定到viewpager的三个片段

ProductLocatorHomeWidgetFragment

public class ProductLocatorHomeWidgetFragment extends Fragment {
int fragVal;
int storeId;
String storeName, storeLat, storeLong, retail_store_id;
TextView mProductLocatorClickZone;
StoreList sList;

public static ProductLocatorHomeWidgetFragment init(int val) {
    ProductLocatorHomeWidgetFragment productLocatorFragment = new ProductLocatorHomeWidgetFragment();
    Bundle args = new Bundle();
    args.putInt("prodLocator", val);
    productLocatorFragment.setArguments(args);
    return productLocatorFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  //  fragVal = getArguments() != null ? getArguments().getInt("prodLocator") : 1;
    sList = new StoreList();
}

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

    mProductLocatorClickZone = (TextView) layoutView.findViewById(R.id.editSearchItemNotLoggedIn);

    mProductLocatorClickZone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sList = LandingPageFragment.storeList;
            if(sList.getId() != null){
                storeId = Integer.parseInt(sList.getId());
                storeLat = sList.getLatitude();
                storeLong = sList.getLongitude();
                storeName = sList.getName();

                Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
                FlurryTrackerHelper.onProductLocatorWidget();
                mIntent.putExtra("store_id", String.valueOf(storeId));
                mIntent.putExtra("store_lat", storeLat);
                mIntent.putExtra("store_lng", storeLong);
                mIntent.putExtra("retail_id", retail_store_id);
                startActivity(mIntent);
            }
            else if (sList.getId() == null) {
                if (LocalDb.getStoreId() > 0) {
                    storeId = LocalDb.getStoreId();
                    storeLat = LocalDb.getStoreLat();
                    storeLong = LocalDb.getStoreLng();
                    storeName = LocalDb.getMyStoreName();
                    Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
                    FlurryTrackerHelper.onProductLocatorWidget();
                    mIntent.putExtra("store_id", String.valueOf(storeId));
                    mIntent.putExtra("store_lat", storeLat);
                    mIntent.putExtra("store_lng", storeLong);
                    mIntent.putExtra("retail_id", retail_store_id);
                    startActivity(mIntent);
                }
            }
            else {
                StoreLocatorDetailsSearchFragment storeLocatorDetailsSearchFragment = new StoreLocatorDetailsSearchFragment();
                Bundle b1 = new Bundle();
                b1.putInt("currentFragment", 10);
                storeLocatorDetailsSearchFragment.setArguments(b1);
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
                transaction.replace(R.id.nav_item_fragment_container, storeLocatorDetailsSearchFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        }
    });
    return layoutView;
}
}

MyShoppingListHomeWidgetFragment

public class MyShoppingListHomeWidgetFragment extends Fragment {
    int fragVal;
    EditText mShoppingListClickZone;
    ImageView mShoppinglistScanClickZone;

    public static MyShoppingListHomeWidgetFragment init(int val) {
        MyShoppingListHomeWidgetFragment myShoppingListFragment = new MyShoppingListHomeWidgetFragment();
        Bundle args = new Bundle();
        args.putInt("myShoppingList", val);
        myShoppingListFragment.setArguments(args);
        return myShoppingListFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // fragVal = getArguments() != null ? getArguments().getInt("myShoppingList") : 1;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View layoutView = inflater.inflate(R.layout.shopping_list_widget, container, false);
        mShoppingListClickZone = (EditText) layoutView.findViewById(R.id.editAddItemNotLoggedIn);
        mShoppingListClickZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShoppingListItemsFragment shoppingListItemsFragment = new ShoppingListItemsFragment();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
                transaction.replace(R.id.nav_item_fragment_container, shoppingListItemsFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });

        mShoppinglistScanClickZone = (ImageView) layoutView.findViewById(R.id.imgScannerNotLoggedIn);
        mShoppinglistScanClickZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionHandler.openCamera(getActivity());
            }
        });
        return layoutView;
    }
}

ProductScanHomeWidgetFragment

public class ProductScanHomeWidgetFragment extends Fragment {
    int fragVal;
    LinearLayout mCouponSearchClickZone, mRefillPrescriptionClickZone;
    View mDivider;

    public static ProductScanHomeWidgetFragment init(int val) {
        ProductScanHomeWidgetFragment productScanFragment = new ProductScanHomeWidgetFragment();
        Bundle args = new Bundle();
        args.putInt("prodScan", val);
        productScanFragment.setArguments(args);
        return productScanFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragVal = getArguments() != null ? getArguments().getInt("prodScan") : 1;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View layoutView = inflater.inflate(R.layout.product_scan_widget, container, false);
        mRefillPrescriptionClickZone = (LinearLayout) layoutView.findViewById(R.id.refillPrescriptionClickZone);
        mCouponSearchClickZone = (LinearLayout) layoutView.findViewById(R.id.couponSearchClickZone);
        mCouponSearchClickZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ECouponsViewFragment eCouponsViewFragment = new ECouponsViewFragment();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
                transaction.replace(R.id.nav_item_fragment_container, eCouponsViewFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });

        if (LocalDb.getBannerSupportRefillPrescriptions().equalsIgnoreCase(
                UtilConstants.KEY_WORD_FALSE)) {
            mDivider = layoutView.findViewById(R.id.divider);
            mDivider.setVisibility(View.GONE);
            mRefillPrescriptionClickZone.setVisibility(View.GONE);

        } else {

            mRefillPrescriptionClickZone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AddPharmacyFragment addPharmacyFragment = new AddPharmacyFragment();
                    FragmentTransaction transaction = getFragmentManager().beginTransaction();
                    transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
                    transaction.replace(R.id.nav_item_fragment_container, addPharmacyFragment);
                    transaction.addToBackStack(null);
                    transaction.commit();
                }
            });
        }
        return layoutView;
    }
}

1 个答案:

答案 0 :(得分:0)

我能够使用FragmentStatePagerAdapter而不是FragmentPagerAdapter来解决这个问题。

所以我删除了LadingPageLoggedOut中的旧FragmentPagerAdapter并将其替换为

<Grid Grid.Row="1" x:Name="btmtp" VerticalAlignment="Bottom">