我想在单击后退按钮时从其他片段返回默认片段,但我无法返回到上一个片段。如何实现?
EduHunt课程主要课程
public class EduHunt extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
TextView toolBarTitle;
ImageView toolBarLogo;
private Fragment mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edu_hunt);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolBarLogo = (ImageView) findViewById(R.id.toolbarlogo);
toolBarTitle = (TextView) findViewById(R.id.toolbartitle);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new Search());
tx.commit();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.search:
fragmentClass = Search.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Search");
break;
case R.id.settings:
fragmentClass = Settings.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("About");
break;
case R.id.register:
fragmentClass = Register.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Register Now");
break;
case R.id.nearme:
fragmentClass = NearMe.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Near Me");
break;
default:
fragmentClass = Search.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.our_team:
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.activity_our_team);
dialog.show();
return true;
case R.id.feedback:
startActivity(new Intent(EduHunt.this, SendFeedback.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.education_hunt, menu);
return true;
}
@Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.flContent);
if(!(fragment instanceof Search )){
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new Search());
tx.commit();
}
}
}
我希望在从任何其他片段支持时回到搜索片段(默认片段),即关于
关于
public class About extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
LinearLayout collegeAffiliation;
ImageView phoneCalls, sendEmails, weblink;
public TextView aboutName, aboutLocation, aboutNumber, aboutEmail, aboutWebsite, aboutCategory, aboutAffiliation;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_about, container, false);
collegeAffiliation = (LinearLayout) v.findViewById(R.id.collegeAffiliation);
aboutName = (TextView) v.findViewById(R.id.about_school_name);
aboutLocation = (TextView) v.findViewById(R.id.about_school_location);
aboutNumber = (TextView) v.findViewById(R.id.about_school_number);
aboutCategory = (TextView) v.findViewById(R.id.about_school_category);
aboutAffiliation = (TextView) v.findViewById(R.id.about_college_affiliation);
aboutEmail = (TextView) v.findViewById(R.id.about_school_email);
aboutWebsite = (TextView) v.findViewById(R.id.about_school_website);
phoneCalls = (ImageView) v.findViewById(R.id.phonecalls);
sendEmails = (ImageView) v.findViewById(R.id.sendEmails);
weblink = (ImageView) v.findViewById(R.id.weblink);
mMapView = (MapView) v.findViewById(R.id.mapview);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
aboutName.setText(ourSchool.getSchoolName());
aboutLocation.setText(ourSchool.getSchoolAddress() + "," + ourSchool.getSchoolDistrict() + "," + ourSchool.getSchoolCountry());
aboutNumber.setText(ourSchool.getSchoolPhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourSchool.getSchoolType());
aboutEmail.setText(ourSchool.getSchoolEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourSchool.getSchoolWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setWeblink();
}
});
LatLng schoollatlng = new LatLng(ourSchool.getLatitude(), ourSchool.getLongitude());
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title(ourSchool.getSchoolName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
collegeAffiliation.setVisibility(View.VISIBLE);
aboutName.setText(ourCollege.getCollegeName());
aboutLocation.setText(ourCollege.getCollegeAddress() + "," + ourCollege.getCollegeDistrict() + "," + ourCollege.getCollegeCountry());
aboutNumber.setText(ourCollege.getCollegePhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourCollege.getCollegeType());
aboutAffiliation.setText(ourCollege.getCollegeAffiliation());
aboutEmail.setText(ourCollege.getCollegeEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourCollege.getCollegeWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setWeblink();
}
});
LatLng collegelatlng = new LatLng(ourCollege.getLatitude(), ourCollege.getLongtitude());
googleMap.addMarker(new MarkerOptions().position(collegelatlng).title(ourCollege.getCollegeName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(collegelatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
aboutName.setText(ourUniversity.getUniversityName());
aboutLocation.setText(ourUniversity.getUniversityAddress() + "," + ourUniversity.getUniversityDistrict() + "," + ourUniversity.getUniverstiyCountry());
aboutNumber.setText(ourUniversity.getUniversityPhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourUniversity.getUniversityType());
aboutEmail.setText(ourUniversity.getUniversityEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourUniversity.getUniversityWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setWeblink();
}
});
LatLng unilatlng = new LatLng(ourUniversity.getUniversityLatitude(), ourUniversity.getUniversityLongitude());
googleMap.addMarker(new MarkerOptions().position(unilatlng).title(ourUniversity.getUniversityName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(unilatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
});
return v;
}
public void callPhoneNumber() {
try {
if (Build.VERSION.SDK_INT > 22) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, 101);
return;
}
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourSchool.getSchoolPhone()));
startActivity(callIntent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourCollege.getCollegePhone()));
startActivity(callIntent);
} else
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourUniversity.getUniversityPhone()));
startActivity(callIntent);
} else {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourSchool.getSchoolPhone()));
startActivity(callIntent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourCollege.getCollegePhone()));
startActivity(callIntent);
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourUniversity.getUniversityPhone()));
startActivity(callIntent);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == 101) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
callPhoneNumber();
} else {
Log.e("Permission not Granted", "");
}
}
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
public void sendEmail() {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourSchool.getSchoolEmail(), null));
try {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourCollege.getCollegeEmail(), null));
try {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourUniversity.getUniversityEmail(), null));
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
try {
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
public void setWeblink() {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourSchool.getSchoolWebsite()));
startActivity(intent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourCollege.getCollegeWebsite()));
startActivity(intent);
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourUniversity.getUniversityWebsite()));
startActivity(intent);
}
try {
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
当我通过任何其他片段回来。该应用程序关闭,但我想要 显示默认片段。这可以完成???
答案 0 :(得分:1)
检查onBackPress事件中的片段实例
WHERE x IN (const_1, const_2, ..., const_n)
答案 1 :(得分:0)
您可以使用接口,Backstack listner和onBackPress按照以下方式执行此操作
创建BaseFragment
公共类FlipkartBaseFragment扩展Fragment {
private MainFlipkartActivity activity;
private ChangeCurrentFragment changeCurrentFragment;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = (MainFlipkartActivity) getActivity();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof ChangeCurrentFragment)
changeCurrentFragment = (ChangeCurrentFragment) context;
}
@Override
public void onDetach() {
super.onDetach();
changeCurrentFragment=null;
}
public ChangeCurrentFragment onChangeCurrentFragment(){
return changeCurrentFragment;
}
public MainFlipkartActivity getBaseActivity() {
return activity;
}
}
然后使用BaseFragment扩展所有片段 在片段中,您可以将一个片段转换为其他片段 ((MainFlipkartActivity)getBaseActivity())。onFragmentChangeListener(new TwoFKTFragment(),“1”+ new Random()。nextInt());
然后像这样实现MainActivity
public class MainFlipkartActivity extends AppCompatActivity
implements FragmentManager.OnBackStackChangedListener,ChangeCurrentFragment
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getSupportFragmentManager().addOnBackStackChangedListener(this);
if (null == savedInstanceState) {
HomeFragment cameraImportFragment = new HomeFragment();
manageFragment(cameraImportFragment, Const.TAG_HOME);
}
}
@Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
} else {
super.onBackPressed();
}
}
}
public void manageFragment(Fragment fragment, String tag)
{
FragmentManager fragmentManager=getSupportFragmentManager();
// String f_name=fragment.getClass().getName();
if(!fragmentManager.popBackStackImmediate(tag,0))
{
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragment, tag);
ft.addToBackStack(tag);
ft.commit();
}
}
@Override
public void onFragmentChangeListener(Fragment fragment, String tag) {
manageFragment(fragment,tag);
}
@Override
public void onBackStackChanged() {
FragmentManager fragmentManager=getSupportFragmentManager();
Fragment fr = fragmentManager.findFragmentById(R.id.frame_container);
if(fr!=null){
fr.onResume();
}
}
答案 2 :(得分:0)
要替换片段,如果要返回上一个片段传递addToBackStack = true
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getSupportFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getSupportFragmentManager().popBackStack();
}
return isPop;
}
将此代码放入backpress的主要活动
@Override
public void onBackPressed() {
if(!popFragment()) {
super.onBackPressed();
}
}