我在操作栏中的后退按钮有问题片段
我的代码片段:
public class Server extends Fragment {
View view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_server, container, false);
Button server = (Button) view.findViewById(R.id.status);
/** Button Check Status Server **/
server.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(view.getContext(), ServerStatus.class);
startActivityForResult(myIntent, 0);
getActivity().finish();
}
});
return view;
}
}
我的活动代码:
public class ServerStatus extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_status);
}
}
我在Fragment中的代码
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new Account();
break;
case 1:
objFragment = new AllNews();
break;
case 2:
objFragment = new Server();
break;
case 3:
objFragment = new Account();
break;
case 4:
objFragment = new Account();
break;
case 5:
objFragment = new Account();
break;
case 6:
objFragment = new About();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container,objFragment)
.commit();
}
每次单击后退按钮时,程序始终关闭。我已经尝试过使用:
getActionBar().setDisplayHomeAsUpEnabled(true);
和此:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
有人可以帮我修理我的程序吗?
答案 0 :(得分:1)
编辑:关于交叉活动导航,您不应该以这种方式使用startActivityForResult()
。请尝试使用startActivity()
。如果您为结果启动活动,则调用活动将等待onActivityResult()
回调,并且不应该完成。
在清单文件中,您应该将片段的活动声明为ServerStatus
的父活动,以启用后退导航。你不应该需要NavUtils。
如果要在活动中启用片段导航,则必须将片段事务添加到backstack:
getFragmentManager().beginTransaction().addToBackStack(null).replace(...).commit();
然后您必须在getFragmentManager().popBackStack()
中致电onOptionsItemSelected()
以启用操作栏的 导航:
@override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
getFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
您可能必须覆盖onBackPressed()
以启用后退导航后退按钮:
@override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() >= 1) {
getFragmentManager().popBackStack(); // return to previous fragment
}
else {
super.onBackPressed(); // Exit application when no fragment is on the backstack
}
}