启动、关闭Activity
启动Activity有如下两个方法:
1:startActivity(Intent intent):
2:startActivityForResult(Intent intent , int resquestCode):
关闭Activity有如下两种方法
1:finish();
2:finishActivity(int requestCode):结束指定的Activity;
Activity的四种加载模式
1. standard:会在Task中启动多次Activity实例
2. singleTop:当需要启动的Activity实例位于Task栈顶时,再次启动将不回创建新的Activity实例
3. singleTask:在同一个Task内,若Activity不存在,则创建!若需要启动的Activity位于栈顶,则Task内无变化!若不位于栈顶,则将位于该Activity上的所有Activity移出Task,将目标Activity位于栈顶!
4. singleInstance:无论从哪个Task中启动目标Activity,只会创建一个目标Activity实例,并且会使用一个全新的栈来加载该Activity实例。
分两种情况:
1.如果将要启动的Activity不存在,系统会先创建一个全新的Task,再创建木匾Activity实例,并将它加入新的Task栈顶
2.如果将要启动的Activity存在,无论他在哪个应用中,系统都会把该Activit所在的Task转到前台,从而使Activity显示出来!
Activity之间传递数据
1. 通过静态变量传递数据:
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.btOpenOtherActivity);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//定义一个意图
Intent intent = new Intent(MainActivity.this,OtherActivity.class);
//改变OtherActivity的三个静态变量的值
OtherActivity.name = "wulianghuan";
OtherActivity.age = "22";
OtherActivity.address = "上海闵行";
startActivity(intent);
}
});
}
}
public class OtherActivity extends Activity {
public static String name;
public static String age;
public static String address;
private TextView text_name;
private TextView text_age;
private TextView text_address;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
text_name = (TextView) findViewById(R.id.name);
text_age = (TextView) findViewById(R.id.age);
text_address = (TextView) findViewById(R.id.address);
//设置文本框的数据
text_name.setText("姓名:"+name);
text_age.setText("年龄:"+age);
text_address.setText("地址:"+address);
}
}
2. 通过全局对象传递数据
public class MainApplication extends Application {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
public class MainActivity extends Activity {
private MainApplication application;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
application = (MainApplication) getApplication();
application.setUsername("sunzn");
}
public void open(View view) {
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
}
}
public class OtherActivity extends Activity {
private TextView tv_data;
private MainApplication application;
private String username;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
application = (MainApplication) getApplication();
username = application.getUsername();
tv_data = (TextView) findViewById(R.id.tv_data);
tv_data.setText("从上一个 Activity 中获取到的数据为:" + username);
}
}