手动回按从FragmentA到Homefragment不工作Android Studio



我有一个名为LatestFragment代码的片段:

public class LatestFragment extends Fragment {
ArrayList<ItemLatest> mListItem;
public RecyclerView recyclerView;
LatestAdapter adapter;
private ProgressBar progressBar;
private LinearLayout lyt_not_found;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_category, container, false);

mListItem = new ArrayList<>();
lyt_not_found = rootView.findViewById(R.id.lyt_not_found);
progressBar = rootView.findViewById(R.id.progressBar);
recyclerView = rootView.findViewById(R.id.vertical_courses_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
recyclerView.setFocusable(false);
recyclerView.setNestedScrollingEnabled(false);
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(new API());
jsObj.addProperty("method_name", "get_latest");
if (JsonUtils.isNetworkAvailable(requireActivity())) {
new getLatest(API.toBase64(jsObj.toString())).execute(Constant.API_URL);
}
setHasOptionsMenu(true);
return rootView;
}
@SuppressLint("StaticFieldLeak")
private class getLatest extends AsyncTask<String, Void, String> {
String base64;
private getLatest(String base64) {
this.base64 = base64;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
showProgress(true);
}
@Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0], base64);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
showProgress(false);
if (null == result || result.length() == 0) {
lyt_not_found.setVisibility(View.VISIBLE);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.ARRAY_NAME);
JSONObject objJson;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
if(objJson.has("status")){
lyt_not_found.setVisibility(View.VISIBLE);
}else {
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJson.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeName(objJson.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeType(objJson.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipePlayId(objJson.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
objItem.setRecipeImageSmall(objJson.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipeImageBig(objJson.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeViews(objJson.getString(Constant.LATEST_RECIPE_VIEW));
objItem.setRecipeTime(objJson.getString(Constant.LATEST_RECIPE_TIME));
objItem.setRecipeCategoryName(objJson.getString(Constant.LATEST_RECIPE_CAT_NAME));
objItem.setRecipeTotalRate(objJson.getString(Constant.LATEST_RECIPE_TOTAL_RATE));
objItem.setRecipeAvgRate(objJson.getString(Constant.LATEST_RECIPE_AVR_RATE));
objItem.setRecipeDirection(objJson.getString(Constant.LATEST_RECIPE_DIRE));
objItem.setRecipeIngredient(objJson.getString(Constant.LATEST_RECIPE_INGREDIENT));
mListItem.add(objItem);
}}
} catch (JSONException e) {
e.printStackTrace();
}
displayData();
}
}
}

private void displayData() {
if (getActivity() != null) {
adapter = new LatestAdapter(getActivity(), mListItem);
recyclerView.setAdapter(adapter);
if (adapter.getItemCount() == 0) {
lyt_not_found.setVisibility(View.VISIBLE);
} else {
lyt_not_found.setVisibility(View.GONE);
}
}
}
private void showProgress(boolean show) {
if (show) {
progressBar.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
lyt_not_found.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_main, menu);

final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
final MenuItem searchMenuItem = menu.findItem(R.id.search);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (!hasFocus) {
searchMenuItem.collapseActionView();
searchView.setQuery("", false);
}
}
});

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
//   finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

和HomeFragment代码:

package com.example.fragment;

public class HomeFragment extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mCatView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mCatView, new RecyclerTouchListener.ClickListener() {
@Override
public void onClick(View view, final int position) {
if (Constant.SAVE_ADS_FULL_ON_OFF.equals("true")) {
Constant.AD_COUNT++;
if (Constant.AD_COUNT == Integer.parseInt(Constant.SAVE_ADS_CLICK)) {
Constant.AD_COUNT = 0;
final InterstitialAd mInterstitial = new InterstitialAd(requireActivity());
mInterstitial.setAdUnitId(Constant.SAVE_ADS_FULL_ID);
AdRequest adRequest;
if (JsonUtils.personalization_ad) {
adRequest = new AdRequest.Builder()
.build();
} else {
Bundle extras = new Bundle();
extras.putString("npa", "1");
adRequest = new AdRequest.Builder()
.addNetworkExtrasBundle(AdMobAdapter.class, extras)
.build();
}
mInterstitial.loadAd(adRequest);
mInterstitial.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
// TODO Auto-generated method stub
super.onAdLoaded();
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
}
public void onAdClosed() {
String categoryName = mCatList.get(position).getCategoryName();
Bundle bundle = new Bundle();
bundle.putString("name", categoryName);
bundle.putString("Id", mCatList.get(position).getCategoryId());
FragmentManager fm = getFragmentManager();
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
subCategoryFragment.setArguments(bundle);
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.hide(HomeFragment.this);
ft.add(R.id.fragment1, subCategoryFragment, categoryName);
ft.addToBackStack(categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
@Override
public void onAdFailedToLoad(int errorCode) {
String categoryName = mCatList.get(position).getCategoryName();
Bundle bundle = new Bundle();
bundle.putString("name", categoryName);
bundle.putString("Id", mCatList.get(position).getCategoryId());
FragmentManager fm = getFragmentManager();
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
subCategoryFragment.setArguments(bundle);
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.hide(HomeFragment.this);
ft.add(R.id.fragment1, subCategoryFragment, categoryName);
ft.addToBackStack(categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
} else {
String categoryName = mCatList.get(position).getCategoryName();
Bundle bundle = new Bundle();
bundle.putString("name", categoryName);
bundle.putString("Id", mCatList.get(position).getCategoryId());
FragmentManager fm = getFragmentManager();
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
subCategoryFragment.setArguments(bundle);
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.hide(HomeFragment.this);
ft.add(R.id.fragment1, subCategoryFragment, categoryName);
ft.addToBackStack(categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
}
}
@Override
public void onLongClick(View view, int position) {
}
}));
btnCat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((ActivityMain) requireActivity()).highLightNavigation(2);
String categoryName = getString(R.string.home_category);
FragmentManager fm = getFragmentManager();
CategoryFragment f1 = new CategoryFragment();
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment1, f1, categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
btnLatest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((ActivityMain) requireActivity()).highLightNavigation(1);
String categoryName = getString(R.string.home_latest);
FragmentManager fm = getFragmentManager();
LatestFragment f1 = new LatestFragment();
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment1, f1, categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
btnMost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((ActivityMain) requireActivity()).highLightNavigation(3);
String categoryName = getString(R.string.menu_most);
FragmentManager fm = getFragmentManager();
MostViewFragment f1 = new MostViewFragment();
assert fm != null;
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment1, f1, categoryName);
ft.commit();
((ActivityMain) requireActivity()).setToolbarTitle(categoryName);
}
});
edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//do something
String st_search = edt_search.getText().toString();
Intent intent = new Intent(getActivity(), SearchActivity.class);
intent.putExtra("search", st_search);
startActivity(intent);
edt_search.getText().clear();
}
return false;
}
});
setHasOptionsMenu(true);
return rootView;
}
@SuppressLint("StaticFieldLeak")
private class Home extends AsyncTask<String, Void, String> {
String base64;
private Home(String base64) {
this.base64 = base64;
}

@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
mScrollView.setVisibility(View.GONE);
}
@Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0], base64);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mProgressBar.setVisibility(View.GONE);
mScrollView.setVisibility(View.VISIBLE);
if (null == result || result.length() == 0) {
showToast(getString(R.string.no_data));
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONObject jsonArray = mainJson.getJSONObject(Constant.ARRAY_NAME);
JSONArray jsonSlider = jsonArray.getJSONArray(Constant.HOME_FEATURED_ARRAY);
JSONObject objJsonSlider;
for (int i = 0; i < jsonSlider.length(); i++) {
objJsonSlider = jsonSlider.getJSONObject(i);
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJsonSlider.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeType(objJsonSlider.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipeCategoryName(objJsonSlider.getString(Constant.LATEST_RECIPE_CAT_NAME));
objItem.setRecipeName(objJsonSlider.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeImageBig(objJsonSlider.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeImageSmall(objJsonSlider.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipePlayId(objJsonSlider.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
mSliderList.add(objItem);
}
JSONArray jsonLatest = jsonArray.getJSONArray(Constant.HOME_LATEST_CAT);
JSONObject objJsonCat;
for (int k = 0; k < jsonLatest.length(); k++) {
objJsonCat = jsonLatest.getJSONObject(k);
ItemCategory objItem = new ItemCategory();
objItem.setCategoryId(objJsonCat.getString(Constant.CATEGORY_ID));
objItem.setCategoryName(objJsonCat.getString(Constant.CATEGORY_NAME));
objItem.setCategoryImageBig(objJsonCat.getString(Constant.CATEGORY_IMAGE_BIG));
objItem.setCategoryImageSmall(objJsonCat.getString(Constant.CATEGORY_IMAGE_SMALL));
mCatList.add(objItem);
}
JSONArray jsonPopular = jsonArray.getJSONArray(Constant.HOME_LATEST_ARRAY);
JSONObject objJson;
for (int l = 0; l < jsonPopular.length(); l++) {
objJson = jsonPopular.getJSONObject(l);
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJson.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeName(objJson.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeType(objJson.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipePlayId(objJson.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
objItem.setRecipeImageSmall(objJson.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipeImageBig(objJson.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeViews(objJson.getString(Constant.LATEST_RECIPE_VIEW));
objItem.setRecipeTime(objJson.getString(Constant.LATEST_RECIPE_TIME));
objItem.setRecipeAvgRate(objJson.getString(Constant.LATEST_RECIPE_AVR_RATE));
objItem.setRecipeTotalRate(objJson.getString(Constant.LATEST_RECIPE_TOTAL_RATE));
objItem.setRecipeCategoryName(objJson.getString(Constant.LATEST_RECIPE_CAT_NAME));
mLatestList.add(objItem);
}
JSONArray jsonPopularMost = jsonArray.getJSONArray(Constant.HOME_MOST_ARRAY);
JSONObject objJsonMost;
for (int l = 0; l < jsonPopularMost.length(); l++) {
objJsonMost = jsonPopularMost.getJSONObject(l);
ItemLatest objItem = new ItemLatest();
objItem.setRecipeId(objJsonMost.getString(Constant.LATEST_RECIPE_ID));
objItem.setRecipeName(objJsonMost.getString(Constant.LATEST_RECIPE_NAME));
objItem.setRecipeType(objJsonMost.getString(Constant.LATEST_RECIPE_TYPE));
objItem.setRecipePlayId(objJsonMost.getString(Constant.LATEST_RECIPE_VIDEO_PLAY));
objItem.setRecipeImageSmall(objJsonMost.getString(Constant.LATEST_RECIPE_IMAGE_SMALL));
objItem.setRecipeImageBig(objJsonMost.getString(Constant.LATEST_RECIPE_IMAGE_BIG));
objItem.setRecipeViews(objJsonMost.getString(Constant.LATEST_RECIPE_VIEW));
objItem.setRecipeTime(objJsonMost.getString(Constant.LATEST_RECIPE_TIME));
objItem.setRecipeAvgRate(objJsonMost.getString(Constant.LATEST_RECIPE_AVR_RATE));
objItem.setRecipeTotalRate(objJsonMost.getString(Constant.LATEST_RECIPE_TOTAL_RATE));
objItem.setRecipeCategoryName(objJsonMost.getString(Constant.LATEST_RECIPE_CAT_NAME));
mMostList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setResult();
}
}
}
private void setResult() {
if (getActivity() != null) {
mLatestAdapter = new HomeAdapter(getActivity(), mLatestList);
mLatestView.setAdapter(mLatestAdapter);
homeMostAdapter = new HomeMostAdapter(getActivity(), mMostList);
mMostView.setAdapter(homeMostAdapter);
homeCategoryAdapter = new HomeCategoryAdapter(getActivity(), mCatList);
mCatView.setAdapter(homeCategoryAdapter);
if (!mSliderList.isEmpty()) {
mViewPager.setAdapter(mAdapter);
if (mSliderList.size() >= 3) {
mViewPager.setCurrentItem(1);
}
}
}
}
private class CustomViewPagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
private CustomViewPagerAdapter() {
// TODO Auto-generated constructor stub
inflater = requireActivity().getLayoutInflater();
}
@Override
public int getCount() {
return mSliderList.size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
View imageLayout = inflater.inflate(R.layout.row_slider_item, container, false);
assert imageLayout != null;
ImageView image = imageLayout.findViewById(R.id.image);
TextView text = imageLayout.findViewById(R.id.text_title);
TextView text_cat = imageLayout.findViewById(R.id.text_cat_title);
LinearLayout lytParent = imageLayout.findViewById(R.id.rootLayout);
text.setText(mSliderList.get(position).getRecipeName());
text_cat.setText(mSliderList.get(position).getRecipeCategoryName());
Picasso.get().load(mSliderList.get(position).getRecipeImageBig()).into(image);
imageLayout.setTag(EnchantedViewPager.ENCHANTED_VIEWPAGER_POSITION + position);
lytParent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopUpAds.ShowInterstitialAds(getActivity(), mSliderList.get(position).getRecipeId());
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
(container).removeView((View) object);
}
}
public void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_profile, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
//   finish();
return true;
case R.id.menu_profile:
if (MyApp.getIsLogin()) {
Intent intent_edit = new Intent(getActivity(), ProfileEditActivity.class);
startActivity(intent_edit);
} else {
final PrettyDialog dialog = new PrettyDialog(requireActivity());
dialog.setTitle(getString(R.string.dialog_warning))
.setTitleColor(R.color.dialog_text)
.setMessage(getString(R.string.login_require))
.setMessageColor(R.color.dialog_text)
.setAnimationEnabled(false)
.setIcon(R.drawable.pdlg_icon_close, R.color.dialog_color, new PrettyDialogCallback() {
@Override
public void onClick() {
dialog.dismiss();
}
})
.addButton(getString(R.string.dialog_ok), R.color.dialog_white_text, R.color.dialog_color, new PrettyDialogCallback() {
@Override
public void onClick() {
dialog.dismiss();
Intent intent_login = new Intent(getActivity(), SignInActivity.class);
intent_login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent_login);
}
})
.addButton(getString(R.string.dialog_no), R.color.dialog_white_text, R.color.dialog_color, new PrettyDialogCallback() {
@Override
public void onClick() {
dialog.dismiss();
}
});
dialog.setCancelable(false);
dialog.show();
}
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
}

当它加载LatestFragment时,我在android设备中按下应用程序Exit,如何从LatestFragment反传到HomeFragment感谢

有没有一种方法可以在Android Fragment中实现onBackPressed((,类似于我们在Android Activity中实现的方法?

由于碎片生命周期没有onBackPressed((。有没有其他替代方法可以在Android 3.5片段中超越BackPressed((?

PLease change in HomeFragmentft.replace(R.id.fragment1, f1, categoryName);

ft.add(R.id.fragment1, f1, categoryName);

它将LatestFragment添加到堆栈中,因此当您从LatestFragment按下后退按钮时,它将显示HomeFragment,因为HomeFragment仍在堆栈中

相关内容

  • 没有找到相关文章

最新更新