嗨,我的主活动中有 Menu Drawer 并有 2 个 Fragment ,第一个 Fragment 包含标签栏,第二个 Fragment 很简单。第二个片段简单片段。
当我在第二个片段和返回堆栈返回按钮时,我会弹出最后一个片段,它会给我错误非法参数异常。
这是主类(菜单抽屉):
public class HomeActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private SessionCreator m_session;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private static String[] mPlanetTitles = {"NewsFeed","Profile", "Worlds", "Leaderboard",
"Map", "Feedback", "Settings"};
boolean btn_back = true;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
mTitle = mDrawerTitle = getTitle();
//mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.drawer_menu, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(2);
}
Common.setObject(mDrawerLayout, mDrawerList);
getFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
// TODO Auto-generated method stub
Fragment f = getFragmentManager().findFragmentById(R.id.content_frame);
if(f!=null){
updateTitelandDrawer(f);
}
}
private void updateTitelandDrawer(Fragment f) {
// TODO Auto-generated method stub
String fragclassName = f.getClass().getName();
Log.d("CheckFragmentStatus", ""+f.toString());
}
});
}
/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = null;
Bundle args;
AppData mApp = (AppData) getApplicationContext();
String szUserId = mApp.getUserId();
switch (position) {
case 0:// news feed
// update the main content by replacing fragments
// requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
fragment = new NewsfeedActivity();
args = new Bundle();
args.putString("userId", szUserId);
fragment.setArguments(args);
break;
case 1:// profile
fragment = new ProfileDetailsActivity();
args = new Bundle();
args.putString("userId", szUserId);
args.putString("profileId", szUserId);
fragment.setArguments(args);
break;
case 2:// world
// update the main content by replacing fragments
fragment = new WorldsMainActivity();
args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
break;
default:
getActionBar()
.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
fragment = new PlanetFragment();
args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
}
// call fragment class
replaceFragment(fragment);
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.coming_soon, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = mPlanetTitles[i];
getActivity().setTitle(planet);
return rootView;
}
}
private void replaceFragment (Fragment fragment){
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);
if (!fragmentPopped) {
transaction.replace(R.id.content_frame, fragment);
}
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack(null);
transaction.commit();
}
// handle fragment navigation backstack push/pop operation
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (getFragmentManager().getBackStackEntryCount() == 1) {
Log.d("MyHomeBackStack", ""
+ getFragmentManager().getBackStackEntryCount());
if (btn_back) {
Toast.makeText(getApplicationContext(), "Press Again",
Toast.LENGTH_LONG).show();
btn_back = false;
} else {
Exitdialog_message("Do you want to exit?");
}
} else {
super.onBackPressed();
}
}
//application exit dialog box
@SuppressWarnings("deprecation")
public void Exitdialog_message(String string) {
final AlertDialog alertDialog = new AlertDialog.Builder(
HomeActivity.this).create();
alertDialog.setTitle(getResources().getString(R.string.app_name));
alertDialog.setMessage(string);
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
});
alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
}
这是我的片段类 1。
public class NewsfeedActivity extends Fragment {
// Declaring our tabs and the corresponding fragments.
ActionBar.Tab ownNF, groupNF, publicNF;
Fragment ownFragment = new NewsFeedOwn();
Fragment groupFragment = new NewsFeedGroups();
Fragment publicFragment = new NewsFeedPublic();
ActionBar actionBar;
SessionCreator session;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.newsfeed_main, container,false);
return myInflatedView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// Asking for the default ActionBar element that our platform supports.
actionBar = getActivity().getActionBar();
// Screen handling while hiding ActionBar icon.
actionBar.setDisplayShowHomeEnabled(true);
// Screen handling while hiding Actionbar title.
actionBar.setDisplayShowTitleEnabled(true);
actionBar.removeAllTabs();
// Creating ActionBar tabs.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Setting custom tab icons.
ownNF = actionBar.newTab().setIcon(R.drawable.nf_own_blue);
groupNF = actionBar.newTab().setIcon(R.drawable.nf_group_blue);
publicNF = actionBar.newTab().setIcon(R.drawable.nf_public_blue);
((NewsFeedOwn)ownFragment).setParentFrag(getActivity());
((NewsFeedOwn)ownFragment).setFrag(this);
((NewsFeedGroups)groupFragment).setParentFrag(getActivity());
((NewsFeedGroups)groupFragment).setFrag(this);
((NewsFeedPublic)publicFragment).setParentFrag(getActivity());
((NewsFeedPublic)publicFragment).setFrag(this);
// Setting tab listeners.
ownNF.setTabListener(new NewsfeedTabListener(ownFragment));
groupNF.setTabListener(new NewsfeedTabListener(groupFragment));
publicNF.setTabListener(new NewsfeedTabListener(publicFragment));
// Adding tabs to the ActionBar.
actionBar.addTab(ownNF);
actionBar.addTab(groupNF);
actionBar.addTab(publicNF);
}
public String getUserId()
{
// get user id and profile id
Bundle data = getArguments();
String szUserId = data.getString("userId");
return szUserId;
}
public void executeGetNewsFeedTask(int nsType, NewsFeedFragment frag)
{
GetNewsFeedTask trickCmd = new GetNewsFeedTask(nsType, frag);
trickCmd.execute();
}
@Override
public void onDestroyView() {
// TODO Auto-generated method stub
//getActivity().getActionBar().removeAllTabs();
// getActivity().getActionBar().removeAllTabs();
// getActivity().getActionBar().hide();
// Fragment mFrag = new NewsfeedActivity();
// getFragmentManager().beginTransaction().remove(mFrag).commit();
super.onDestroyView();
}
}
这是第二个片段类:
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,Bundle savedInstanceState) {
Log.d("ProfileBackStackAction", ""+getFragmentManager().getBackStackEntryCount());
if(getFragmentManager().getBackStackEntryCount()>1){
Toast.makeText(getActivity(), "Called", Toast.LENGTH_LONG).show();
getActivity().getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
// getActivity().getActionBar().setHomeButtonEnabled(true);
// getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
// getActivity().getActionBar().setDisplayUseLogoEnabled(false);
}else{
getActivity().getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
}
View myInflatedView = inflater.inflate(R.layout.profile_details_main, container,false);
init(myInflatedView);
m_bAllTricksView = false;
// get user id and profile id
Bundle data = getArguments();
szUserId = data.getString("userId");
szProfileId = data.getString("profileId");
m_lvTricks = (ListView) myInflatedView.findViewById(R.id.lvLatestTricks);
adapter = new FollowerListAdapter(getActivity(), trickList);
m_lvTricks.setAdapter(adapter);
m_lvTricks.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
FollowerOrTrickItem trickItem = (FollowerOrTrickItem) parent.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), TrickDetailsActivity.class);
//TODO:: pass trick id, profile id, user id
intent.putExtra("userId", szUserId);
intent.putExtra("profileId", szProfileId);
intent.putExtra("trickId", trickItem.szProfileId);
startActivity(intent);
}
});
m_civProfPic.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("userId", szUserId);
bundle.putString("profileId", szProfileId);
bundle.putString("ImagePath", ImageUrl);
UpdatePicture updatePicture = new UpdatePicture();
updatePicture.setArguments(bundle);
FragmentManager manager = getFragmentManager();
android.app.FragmentTransaction transection = manager.beginTransaction();
transection.replace(R.id.content_frame, updatePicture);
transection.addToBackStack("updatePicture");
transection.commit();
}
});
m_ivCover.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("userId", szUserId);
bundle.putString("profileId", szProfileId);
bundle.putString("ImagePath", CoverImageUrl);
UpdatePicture updateCover = new UpdatePicture();
updateCover.setArguments(bundle);
FragmentManager manager = getFragmentManager();
android.app.FragmentTransaction transection = manager.beginTransaction();
transection.replace(R.id.content_frame, updateCover);
transection.addToBackStack("updateCover");
transection.commit();
}
});
// send request to fetch worlds and fetch status of each three levels from response
String strURL = GlobalMethod.TokenGenerator() + "&action=getProfileData";
ProfileCmdTask taskCmd = new ProfileCmdTask();
taskCmd.execute(szUserId, szProfileId, strURL);
return myInflatedView;
}
这是我的日志猫,当我从第二个片段返回到第一个片段时,标签栏显示空白页或列表视图,当我尝试移动第二个标签时,它会给我非法参数异常问题
这是我的日志:
06-18 02:19:03.004: E/AndroidRuntime(4020): FATAL EXCEPTION: main
06-18 02:19:03.004: E/AndroidRuntime(4020): Process: com.prostart.zoneln, PID: 4020
06-18 02:19:03.004: E/AndroidRuntime(4020): java.lang.IllegalArgumentException: No view found for id 0x7f0b0072 (com.prostart.zoneln:id/newsfeed_root) for fragment NewsFeedGroups{530daf0c #2 id=0x7f0b0072}
06-18 02:19:03.004: E/AndroidRuntime(4020): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:882)
06-18 02:19:03.004: E/AndroidRuntime(4020): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
06-18 02:19:03.004: E/AndroidRuntime(4020): at android.app.BackStackRecord.run(BackStackRecord.java:684)
06-18 02:19:03.004: E/AndroidRuntime(4020): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
06-18 02:19:03.004: E/AndroidRuntime(4020): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
06-18 02:19:03.004: E/AndroidRuntime(4020): at android.os.Handler.handleCallback(Handler.java:733)
06-18 02:19:03.004: E/AndroidRuntime(4020): at android.os.Handler.dispatchMessage(Handler.java:95)
06-18 02:19:03.004: E/AndroidRuntime(4020): at android.os.Looper.loop(Looper.java:136)
06-18 02:19:03.004: E/AndroidRuntime(4020): at android.app.ActivityThread.main(ActivityThread.java:5001)
06-18 02:19:03.004: E/AndroidRuntime(4020): at java.lang.reflect.Method.invokeNative(Native Method)
06-18 02:19:03.004: E/AndroidRuntime(4020): at java.lang.reflect.Method.invoke(Method.java:515)
06-18 02:19:03.004: E/AndroidRuntime(4020): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
06-18 02:19:03.004: E/AndroidRuntime(4020): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
06-18 02:19:03.004: E/AndroidRuntime(4020): at dalvik.system.NativeStart.main(Native Method)
这个链接展示了我的后台堆栈是如何工作的