一、用intent打开新窗口
Intent(content1, content2)
content1:原窗口
content2:跳转的目的窗口
//用intent打开新窗口
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View source){
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
二、用bundle在窗口间传递数据
//用bundle传递数据
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View source){
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle data = new Bundle();
data.putString("str", "test");
intent.putExtras(data);
startActivity(intent);
}
}
}
获取数据
Intent intent = getIntent();
Bundle data = intent.getExtras();
String str = (String)data.getString("str");
三、用startActivityForResult打开窗口
step 01 在原窗口的onCreate方法中用startActivityForResult方法打开窗口,替换原来的startActivity函数。
startActivityForResult(Intent intent, int requestCode) : requestCode->请求码,用于认证
startActivityForResult(intent, 0);
step 02 重写原窗口的OnActivityResult方法
OnActivityResult(int requestCode, int resultCode, Intent intent)
requestCode->请求码
resultCode->返回码
intent->目标窗口的intent返回
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent){
if(requestCode == 0 && resultCode == 0){
Bundle data = intent.getExtras();
Type temp = data.getType(key);
...
}
}
step 03 目标窗口代码
Intent intent = getIntent();
Bundle data = new Bundle();
data.putType(key, sth);
intent.putExtras(data);
DestActivity.this.setResult(0, intent);
DestActivity.this.finish();
四、利用Intent-filter
step 01 设置Manifest.xml文件
在被调用窗口的activity声明中设置intent-filter
<activity android:name=".SecondActivity"
android:lable="被调用的窗口">
<intent-filter>
<action andriod:name="com.will.intent.action.Test" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
step 02 在主窗口中调用被调窗口
Intent intent = new Intent();
intent.setAction("com.will.intent.action.Test");
intent.addCategory("android.intent.category.DEFAULT");
startActivity(intent);