在Android中,获取Activity的方法主要有以下几种:
startActivity()
方法从一个Activity启动另一个Activity。例如:Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivity(intent);
startActivityForResult()
方法从一个Activity启动另一个Activity,并期望从目标Activity获取结果。例如:Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivityForResult(intent, REQUEST_CODE);
ActionBar
的setDisplayHomeAsUpEnabled()
和onOptionsItemSelected()
方法在导航栏中添加返回按钮,点击返回按钮时返回上一个Activity。例如:@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
Fragment
的getParentFragmentManager()
方法获取父FragmentManager,然后使用beginTransaction()
方法进行Activity之间的跳转。例如:FragmentManager fragmentManager = getParentFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, new TargetFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Context
的startActivity()
方法从非Activity类中启动Activity。例如:public class UtilityClass {
public static void startTargetActivity(Context context) {
Intent intent = new Intent(context, TargetActivity.class);
context.startActivity(intent);
}
}
然后在需要启动Activity的地方调用UtilityClass.startTargetActivity(context)
。