将主屏幕时,重复的动作在Android应用程序
简介:
我的客户需要在整个应用程序的一些组件,如navigationDrawer
,toolbar
。所以我有一个MainActivity
有两个toolbar
(顶部/底部)和两个导航抽屉(左/右)。所有其他屏幕包含fragments
,我在MainActivity
更改。我有一个小问题,就是一些动作被重复。
案例: 在一些fragments
当用户执行一个动作即
1:用户按下“放入购物车” button
,按家庭button
是在toolbar
底部的“添加到购物车” button
运行代码两次(一旦点击按钮,一旦进入主屏幕),所以我的物品被添加到购物车两次。
2:在另一个片段我有“申请优惠券” checkbox
当用户检查checkbox
的AlertDialog
出现,当用户进入主屏幕AlertDialog
再次出现在主屏幕。将主屏幕时,重复的动作在Android应用程序
我只是重新创建回家按钮按下的主要活动与recreate();
我检查的代码,但不明白为什么这些动作重复。如果有人遇到相同或类似的问题,请指导我如何解决这个问题。任何帮助,将不胜感激。
如果我需要显示代码告诉我哪个部分?
编辑: 内的片段车详细onCreateView
useCoupon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
createAndShowCustomAlertDialog();
}
}
});
序列这个代码是主要活动(主碎片)=>产品分片=>车详细破片。
编辑2:MainActivity
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
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;
}
}
我删除全局变量和因长度的一些方法。
回答:
您不应该在这里使用recreate()方法,因为它会强制活动重新加载所有内容。只需使用意图呼叫您的家庭活动,即可解决此问题。
回答:
从@Akash Khatri的提示我用切换到mainFragment
,现在罚款。其实@Akash对目前的一切都是对的recreate();
但是当我在MainActivity的OnCreate中设置主要片段时。所以,很难注意到Android首先重新创建所有内容,并且很快就将其称为主要片段。
我不使用意图再次启动相同的活动因为切换片段更方便。而且我还通过一些额外的东西,我会用新的意图散失。
以上是 将主屏幕时,重复的动作在Android应用程序 的全部内容, 来源链接: utcz.com/qa/266590.html