安卓intent跳转
intent传值跳转
1,显式跳转
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
startActivity(intent);
第一个参数为原界面,第二个参数为跳转界面,intent需要使用start函数来使用
2,隐式跳转
隐式intent跳转
打开AndroidManifest.xml写入一下代码
<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="com.example.activitytest.AVTION_START"/>
<category android:name="android.intent.category.DEFAULT"/>
//若设定了category则加上下面的一行代码
<category android:name="com.example.activitytest.MY" />
</intent-filter>
</activity>
在Firstactivity中使用intent跳转到secondactivity
Intent intent=new Intent("com.example.activitytest.AVTION_START");
intent.addCategory("com.example.activitytest.MY");//设置Category,可不写
startActivity(intent);
其他隐式intent用法
1>网站的跳转
public void onClick(View view){
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);
}
设置intent为Intent.ACTION_VIEW对象,然后调用setData函数该函数需要传入一个URI对象,使用Uri.Parse将一个网址转化为一个URI对象
2>电话簿的跳转
public void onClick(View view){
Intent intent=new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
}
电话簿的intent的类型是ACTION_DIAL;
3,intent数据的传递
1>传递数据给下一个活动
在firstActivity界面中将数据写入到intent中保存
public void onClick(View view){
String s="王怀宇";
Intent intent=new Intent("com.example.activitytest.AVTION_START");
intent.addCategory("com.example.activitytest.MY");
intent.putExtra("data",s);
startActivity(intent);
}
在secondActivity中将intent中的值取出
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent=getIntent();
String data=intent.getStringExtra("data");
Log.d("SecondActivity",data);
2>传递数据给上一个活动
FirstActivity向SecondActivity跳转有于要返回值所以使用startActivityForResult跳转,该函数接收两个参数第一个是intent第二个是请求码,唯一即可。
public void onClick(View view){
Intent intent=new Intent("com.example.activitytest.AVTION_START");
intent.addCategory("com.example.activitytest.MY");
startActivityForResult(intent,1);
}
在secondActivity中使用button返回或直接点击返回(onBackPressed)写入如下代码setResult函数是专门用于返回值得函数,第一个是活动返回的处理结果RESULT_OK或者RESULT_CANCELED第二个参数是intent对象
public void onClick(View view){
Intent intent=new Intent();
intent.putExtra("re","hellow");
setResult(RESULT_OK,intent);
finish();
}
public void onBackPressed() {
Intent intent=new Intent();
intent.putExtra("re","hellow");
setResult(RESULT_OK,intent);
finish();
}
返回到FirstActivity中后需要接收返回的数据重写onActivityResult函数,第一个参数是请求码,第二个是处理结果,使用data.getStringExtra("re");就可以成功接收数据了
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case 1:
if(resultCode==RESULT_OK){
String re=data.getStringExtra("re");
Log.d("FirstActivity",re);
}
break;
default:
}
}