2017-12-27 63 views
0

イントロ:
私のクライアントはnavigationDrawertoolbarのようなアプリケーション間でいくつかのコンポーネントが必要です。だからMainActivityは2つのtoolbar(上/下)と2つのナビゲーション引き出し(左/右)を持っています。他のすべての画面はMainActivityに変更されたfragmentsで構成されています。私は、いくつかのアクションが重複しているという少し問題があります。
ケース:ユーザーはすなわち
1アクションを実行するいくつかのfragmentstoolbar底にある
ユーザーを押し、「カートに入れる」buttonを押し自宅button、「カートに入れる」button実行のコード私の商品がカートに2回追加されるように2回(ボタンを1回クリックして、一度ホーム画面に)クリックします。
2:私は、「クーポンを適用」を持つ別のフラグメントではcheckboxは、ユーザーのチェックがcheckboxAlertDialogが表示されているとき、ユーザーがホーム画面に行くときAlertDialogは再びホーム画面に表示されます。重複アクションホーム画面に行く

私は単に私がコードをチェックしますが、それらのアクションが重複する理由を理解することはできませんrecreate();

でホームボタンを押し上の主な活動を再現しています。誰かが同じまたは少し似たような問題に直面した場合、私にそれに取り組む方法を教えてください。どんな助けもありがとう。

コードを表示する必要がある場合は、どの部分を教えてください。

編集:このコードの

useCoupon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       if (isChecked) { 
        createAndShowCustomAlertDialog(); 
       } 
      } 
     }); 

断片カート詳細の onCreateView内部配列は、主な活動(主要フラグメント)=>製品FRAG =>カート詳細FRAGあります。

編集2:MainActivity私はグローバル変数と理由の長さのいくつかの方法を取り除い

public class MainFrag extends MyBaseFragment { 

    public MainFrag() {} 

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

     View view = inflater.inflate(R.layout.frag_main, container, false); 
     initUtils(); 
     initViews(view); 
     utils.setupSlider(mPager, indicator, pb, true, true); 

     RecyclerView.LayoutManager mLayoutManager = 
       new LinearLayoutManager(getActivity() 
         , LinearLayoutManager.VERTICAL, false); 
     mRecyclerView.setLayoutManager(mLayoutManager); 
     List<String> keysList = prepareData(); 
     if (keysList.size() > 0 && !keysList.isEmpty()) { 
      mRecyclerView.setAdapter(new MainFragmentAdapter(keysList)); 
     } 

     return view; 
    } 

    private void initViews(View view) { 
     mRecyclerView = view.findViewById(R.id.parent_recycler_view); 
     mPager = view.findViewById(R.id.pager); 
     indicator = view.findViewById(R.id.indicator); 
     pb = view.findViewById(R.id.loading); 
    } 

    private List<String> prepareData() { 
     String responseStr = getHomeExtra(); 
     List<String> keysStr = new ArrayList<>(); 
     try { 
      JSONObject responseObject = new JSONObject(responseStr); 
      utils.printLog("JSON_Response", "" + responseObject); 
      boolean success = responseObject.optBoolean("success"); 
      if (success) { 
       JSONObject homeObject = responseObject.optJSONObject("home"); 
       JSONObject modules = homeObject.optJSONObject("modules"); 

       Iterator<?> keys = modules.keys(); 
       while (keys.hasNext()) { 
        String key = (String) keys.next(); 
        keysStr.add(key); 
        utils.printLog("KeyStr", key); 
       } 
       utils.printLog("ModuleSize", modules.toString()); 
      } else { 
       utils.printLog("SuccessFalse", "Within getCategories"); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
      utils.printLog("JSONEx_MainFragTest", responseStr); 
     } 
     return keysStr; 
    } 
} 

public class MainActivity extends AppCompatActivity implements View.OnClickListener { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     this.utils = new Utils(this); 
     utils.changeLanguage("en"); 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     initViews(); 
     this.context = this; 
     setupToolbar(this); 
     utils.switchFragment(new MainFrag()); 
     setOnClickListener(); 

     initRightMenuData(); 
     initLeftMenuData(); 

     listAdapter = new ExpandableListAdapter(headerListLeft, hashMapLeft, 
       false, loggedInIconList); 
     listViewExpLeft.setAdapter(listAdapter); 
     if (isLoggedIn()) { 
      listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight, 
        loggedInIconList); 
     } else { 
      listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight, 
        NotLoggedInIconList); 
     } 
     listViewExpRight.setAdapter(listAdapterRight); 

     enableSingleSelection(); 
     setExpandableListViewClickListener(); 
     setExpandableListViewChildClickListener(); 

    } 

    private void setOnClickListener() { 
     myAccountTV.setOnClickListener(this); 
     checkoutTV.setOnClickListener(this); 
     discountTV.setOnClickListener(this); 
     homeTV.setOnClickListener(this); 
     searchIcon.setOnClickListener(this); 
     cartLayout.setOnClickListener(this); 
    } 

    private void setExpandableListViewClickListener() { 
     listViewExpRight.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { 
      @Override 
      public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, 
             long id) { 

       utils.printLog("GroupClicked", " Id = " + id); 
       int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition); 
       if (!isLoggedIn()) { 
        if (childCount < 1) { 
         if (groupPosition == 0) { 
          utils.switchFragment(new FragLogin()); 
         } else if (groupPosition == 1) { 
          utils.switchFragment(new FragRegister()); 
         } else if (groupPosition == 2) { 
          utils.switchFragment(new FragContactUs()); 
         } else { 
          recreate(); 
         } 
         drawer.closeDrawer(GravityCompat.END); 
        } 
       } else { 
        if (childCount < 1) { 
         changeFragment(103 + groupPosition); 
         drawer.closeDrawer(GravityCompat.END); 
        } 
       } 

       return false; 
      } 
     }); 

     listViewExpLeft.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { 
      @Override 
      public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { 

       int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition); 

       if (childCount < 1) { 
        MenuCategory textChild = (MenuCategory) parent.getExpandableListAdapter() 
          .getGroup(groupPosition); 
        moveToProductFragment(textChild.getMenuCategoryId()); 
        utils.printLog("InsideChildClick", "" + textChild.getMenuCategoryId()); 

       } 

       return false; 
      } 
     }); 
    } 

    private void setExpandableListViewChildClickListener() { 
     listViewExpLeft.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { 
      @Override 
      public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, 
             int childPosition, long id) { 

       MenuSubCategory subCategory = (MenuSubCategory) parent.getExpandableListAdapter() 
         .getChild(groupPosition, childPosition); 

       moveToProductFragment(subCategory.getMenuSubCategoryId()); 
       utils.printLog("InsideChildClick", "" + subCategory.getMenuSubCategoryId()); 

       return true; 
      } 
     }); 
     listViewExpRight.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { 
      @Override 
      public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { 
       String str = parent.getExpandableListAdapter().getGroup(groupPosition).toString(); 
       UserSubMenu userSubMenu = (UserSubMenu) parent.getExpandableListAdapter() 
         .getChild(groupPosition, childPosition); 
       if (str.contains("Information") || str.contains("معلومات")) { 
        Bundle bundle = new Bundle(); 
        bundle.putString("id", userSubMenu.getUserSubMenuCode()); 
        utils.switchFragment(new FragShowText(), bundle); 
       } else if (str.contains("اللغة") || str.contains("Language")) { 

        recreate(); 
       } else if (str.contains("دقة") || str.contains("Currency")) { 
        makeDefaultCurrencyCall(userSubMenu.getUserSubMenuCode()); 
       } 
       utils.printLog("InsideChildClick", "" + userSubMenu.getUserSubMenuCode()); 
       drawer.closeDrawer(GravityCompat.END); 

       return false; 
      } 
     }); 
    } 

    private void setupToolbar(Context context) { 

     ViewCompat.setLayoutDirection(appbarBottom, ViewCompat.LAYOUT_DIRECTION_RTL); 
     ViewCompat.setLayoutDirection(appbarTop, ViewCompat.LAYOUT_DIRECTION_RTL); 

     String imgPath = Preferences 
       .getSharedPreferenceString(appContext, LOGO_KEY, DEFAULT_STRING_VAL); 
     utils.printLog("Product Image = " + imgPath); 
     if (!imgPath.isEmpty()) { 
      Picasso.with(getApplicationContext()).load(imgPath) 
        .into(logoIcon); 
     } 
     logoIcon.setOnClickListener(this); 

     AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); 
     actionbarToggle(); 
     drawer.addDrawerListener(mDrawerToggle); 

     drawerIconLeft.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if (drawer.isDrawerOpen(GravityCompat.START)) { 
        drawer.closeDrawer(GravityCompat.START); 
       } else { 
        drawer.openDrawer(GravityCompat.START); 
        drawerIconLeft.setScaleX(1); 
        drawerIconLeft.setImageResource(R.drawable.ic_arrow_back_black); 
       } 
      } 
     }); 
     drawerIconRight.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if (drawer.isDrawerOpen(GravityCompat.END)) { 
        drawer.closeDrawer(GravityCompat.END); 
       } else { 
        drawer.openDrawer(GravityCompat.END); 
       } 
      } 
     }); 
    } 

    private void initViews() { 
     drawerIconLeft = findViewById(R.id.drawer_icon_left); 
     drawerIconRight = findViewById(R.id.drawer_icon_right); 
     logoIcon = findViewById(R.id.logo_icon); 
     searchIcon = findViewById(R.id.search_icon); 
     cartLayout = findViewById(R.id.cart_layout); 
     counterTV = findViewById(R.id.actionbar_notification_tv); 

     drawer = findViewById(R.id.drawer_layout); 
     listViewExpLeft = findViewById(R.id.expandable_lv_left); 
     listViewExpRight = findViewById(R.id.expandable_lv_right); 

     appbarBottom = findViewById(R.id.appbar_bottom); 
     appbarTop = findViewById(R.id.appbar_top); 
     myAccountTV = findViewById(R.id.my_account_tv); 
     discountTV = findViewById(R.id.disc_tv); 
     checkoutTV = findViewById(R.id.checkout_tv); 
     homeTV = findViewById(R.id.home_tv); 

     searchView = findViewById(R.id.search_view); 
    } 

    @Override 
    public void onBackPressed() { 

     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else if (drawer.isDrawerOpen(GravityCompat.END)) { 
      drawer.closeDrawer(GravityCompat.END); 
     } else { 
      super.onBackPressed(); 
     } 
    } 

    private void initRightMenuData() { 
     headerListRight = new ArrayList<>(); 
     hashMapRight = new HashMap<>(); 

     String[] notLoggedInMenu = {findStringByName("login_text"), 
       findStringByName("action_register_text"), 
       findStringByName("contact_us_text")}; 
     String[] loggedInMenu = {findStringByName("account"), findStringByName("edit_account_text"), 
       findStringByName("action_change_pass_text"), 
       findStringByName("order_history_text"), 
       findStringByName("logout"), findStringByName("contact_us_text")}; 

     List<UserSubMenu> userSubMenusList = new ArrayList<>(); 
     if (isLoggedIn()) { 
      for (int i = 0; i < loggedInMenu.length; i++) { 
       headerListRight.add(loggedInMenu[i]); 
       hashMapRight.put(headerListRight.get(i), userSubMenusList); 
      } 
     } else { 
      for (int i = 0; i < notLoggedInMenu.length; i++) { 
       headerListRight.add(notLoggedInMenu[i]); 
       hashMapRight.put(headerListRight.get(i), userSubMenusList); 

      } 
     } 
     String responseStr = ""; 
     if (getIntent().hasExtra(KEY_EXTRA)) { 
      responseStr = getIntent().getStringExtra(KEY_EXTRA); 
      utils.printLog("ResponseInInitData", responseStr); 
      try { 
       JSONObject responseObject = new JSONObject(responseStr); 
       boolean success = responseObject.optBoolean("success"); 
       if (success) { 
        try { 
         JSONObject homeObject = responseObject.getJSONObject("home"); 
         JSONArray slideshow = homeObject.optJSONArray("slideshow"); 
         AppConstants.setSlideshowExtra(slideshow.toString()); 
         JSONArray menuRight = homeObject.optJSONArray("usermenu"); 

         for (int z = 0; z < menuRight.length(); z++) { 
          List<UserSubMenu> userSubMenuList = new ArrayList<>(); 
          JSONObject object = menuRight.getJSONObject(z); 
          headerListRight.add(object.optString("name")); 
          JSONArray childArray = object.optJSONArray("children"); 

          for (int y = 0; y < childArray.length(); y++) { 
           JSONObject obj = childArray.optJSONObject(y); 
           userSubMenuList.add(new UserSubMenu(obj.optString("code"), 
             obj.optString("title"), obj.optString("symbol_left"), 
             obj.optString("symbol_right"))); 
          } 
          hashMapRight.put(headerListRight.get(headerListRight.size() - 1), userSubMenuList); 
          utils.printLog("AfterHashMap", "" + hashMapRight.size()); 
         } 

        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } else { 
        utils.showErrorDialog("Error Getting Data From Server"); 
        utils.printLog("SuccessFalse", "Within getCategories"); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
       utils.printLog("JSONObjEx_MainAct", responseStr); 
      } 
     } else { 
      utils.printLog("ResponseExMainActivity", responseStr); 
      throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA); 
     } 

    } 

    private void initLeftMenuData() { 
     headerListLeft = new ArrayList<>(); 
     hashMapLeft = new HashMap<>(); 

     String responseStr = ""; 
     if (getIntent().hasExtra(KEY_EXTRA)) { 
      responseStr = getIntent().getStringExtra(KEY_EXTRA); 
      utils.printLog("ResponseInMainActivity", responseStr); 
      try { 
       JSONObject responseObject = new JSONObject(responseStr); 
       utils.printLog("JSON_Response", "" + responseObject); 
       boolean success = responseObject.optBoolean("success"); 
       if (success) { 
        try { 
         JSONObject homeObject = responseObject.getJSONObject("home"); 

         JSONArray menuCategories = homeObject.optJSONArray("categoryMenu"); 
         utils.printLog("Categories", menuCategories.toString()); 
         for (int i = 0; i < menuCategories.length(); i++) { 

          JSONObject menuCategoryObj = menuCategories.getJSONObject(i); 
          JSONArray menuSubCategoryArray = menuCategoryObj.optJSONArray(
            "children"); 

          List<MenuSubCategory> childMenuList = new ArrayList<>(); 
          for (int j = 0; j < menuSubCategoryArray.length(); j++) { 
           JSONObject menuSubCategoryObj = menuSubCategoryArray.getJSONObject(j); 
           MenuSubCategory menuSubCategory = new MenuSubCategory(
             menuSubCategoryObj.optString("child_id"), 
             menuSubCategoryObj.optString("name")); 
           childMenuList.add(menuSubCategory); 
          } 
          MenuCategory menuCategory = new MenuCategory(menuCategoryObj.optString(
            "category_id"), menuCategoryObj.optString("name"), 
            menuCategoryObj.optString("icon"), childMenuList); 
          headerListLeft.add(menuCategory); 
          hashMapLeft.put(headerListLeft.get(i), menuCategory.getMenuSubCategory()); 
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      utils.printLog("ResponseExMainActivity", responseStr); 
      throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA); 
     } 
    } 

    private void actionbarToggle() { 
     mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawer, 
       R.string.navigation_drawer_open, R.string.navigation_drawer_close) { 

      public void onDrawerClosed(View view) { 
       super.onDrawerClosed(view); 
       drawerIconLeft.setImageResource(R.drawable.ic_list_black); 
       drawerIconLeft.setScaleX(-1); 
      } 

      public void onDrawerOpened(View drawerView) { 
       super.onDrawerOpened(drawerView); 
      } 
     }; 
    } 

    @Override 
    public void onClick(View v) { 
     int id = v.getId(); 

     if (id == R.id.logo_icon) { 
      recreate(); 
     } else if (id == R.id.my_account_tv) { 
      utils.switchFragment(new Dashboard()); 
     } else if (id == R.id.disc_tv) { 
      utils.printLog("From = Main Act"); 
      Bundle bundle = new Bundle(); 
      bundle.putString("from", "mainActivity"); 
      utils.switchFragment(new FragProduct(), bundle); 

     } else if (id == R.id.checkout_tv) { 
      if (isLoggedIn()) { 
       utils.switchFragment(new FragCheckout()); 
      } else { 
       AlertDialog alertDialog = utils.showAlertDialogReturnDialog("Continue As", 
         "Select the appropriate option"); 
       alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, 
         "As Guest", new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialog, int which) { 
           utils.switchFragment(new FragCheckout()); 
          } 
         }); 
       alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, 
         "Login", new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialog, int which) { 
           utils.switchFragment(new FragLogin()); 
          } 
         }); 
       alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, 
         "Register", new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialog, int which) { 
           utils.switchFragment(new FragRegister()); 
          } 
         }); 
       alertDialog.show(); 
      } 
     } else if (id == R.id.home_tv) { 
      recreate(); 
     } else if (id == R.id.search_icon) { 
      startActivityForResult(new Intent(context, SearchActivity.class), SEARCH_REQUEST_CODE); 
     } else if (id == R.id.cart_layout) { 
      Bundle bundle = new Bundle(); 
      bundle.putString("midFix", "cartProducts"); 
      utils.switchFragment(new FragCartDetail(), bundle); 
     } 
    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     if (requestCode == SEARCH_REQUEST_CODE || requestCode == CURRENCY_REQUEST_CODE 
       || requestCode == LANGUAGE_REQUEST_CODE) { 
      if (data != null) { 
       String responseStr = data.getStringExtra("result"); 
       utils.printLog("ResponseIs = " + responseStr); 

       if (responseStr != null) { 
        if (resultCode == Activity.RESULT_OK) { 
         JSONObject response; 
         if (!isJSONString(responseStr)) { 
          try { 
           response = new JSONObject(responseStr); 
           if (requestCode == CURRENCY_REQUEST_CODE) { 
            JSONObject object = response.optJSONObject("currency"); 
            Preferences.setSharedPreferenceString(appContext 
              , CURRENCY_SYMBOL_KEY 
              , object.optString("symbol_left") 
                + object.optString("symbol_right") 
            ); 
            recreate(); 
           } else if (requestCode == LANGUAGE_REQUEST_CODE) { 
            JSONObject object = response.optJSONObject("language"); 
            Preferences.setSharedPreferenceString(appContext 
              , LANGUAGE_KEY 
              , object.optString("code") 
            ); 
            recreate(); 
           } 

          } catch (JSONException e) { 
           e.printStackTrace(); 
          } 
         } else { 
          if (requestCode == SEARCH_REQUEST_CODE) { 
           if (responseStr.isEmpty()) 
            return; 
           Bundle bundle = new Bundle(); 
           bundle.putString("id", responseStr); 
           bundle.putString("from", "fromSearch"); 
           utils.switchFragment(new FragProduct(), bundle); 
          } else { 
           utils.showAlertDialog("Alert", responseStr); 
          } 
         } 
        } else if (resultCode == FORCED_CANCEL) { 
         utils.printLog("WithinSearchResult", "If Success False" + responseStr); 
        } else if (resultCode == Activity.RESULT_CANCELED) { 
         utils.printLog("WithinSearchResult", "Result Cancel" + responseStr); 
        } 
       } 
      } 
     } 
    } 

} 

MainFragment。

+0

メインアクティビティとホームフラグメントを投稿することができます –

+0

これらは長すぎると思われるコードを表示する方法はありますか?それ以外の場合は、ここに貼り付けます。 –

答えて

0

ここでrecreate()メソッドを使用しないでください。これは、アクティビティがすべてをリロードするよう強制するためです。あなたのホーム活動を呼び出すために意図を使用するだけで、この問題を解決するはずです。

+0

私は 'recreate();'を知っているので、そのアクティビティの中にあるものはすべてリロードしますが、後でそのアクティビティに含まれるものはリロードしません。 –

+0

私は、デフォルトで 'MainActivity'に' MainFargment'を持っていると言っていますが、recreate()は 'mainActivity'に添付されていない他の'フラグメント 'ではありません。 –

+0

あなたは、問題? –

0

@Akash Khatriのヒントから、今はmainFragmentとその罰金に切り替えるために使用します。実際に@Akashは正しいですrecreate();現在のところ、私はMainActivityのOnCreateにメインフラグメントを設定していました。それで、Androidが最初にすべてを作り直し、すぐに主要な断片を呼び出すことに気づくのは難しいです。

同じアクティビティを再度開始するためにIntentを使用しません。フラグメントを切り替える方が便利です。そして、私は新しい意図をもって緩んでいくべき余分なものを渡します。