Android学习笔记--3.Intent的使用
2016-08-23 20:20
573 查看
前言:今天学的是利用Intent对象进行页面的跳转,同时也利用Intent进行页面间的数据传递。
1.显示地使用Intent对象,跳转页面
2.隐式地使用 Intent进行页面跳转
这种方法,需要为所要跳转的第二个Activity在AndroidMainfests配置中添加action属性和category属性
3.从第一个页面往第二个页面跳转,利用Intent对象的putExtra方法传数据,这个方法里的两个参数是一个键值对。
4.从第二个页面跳往第一个页面,使用Intent传数据。下面是需要在第二个活动的按钮点击事件中,所需写的代码。
这样的跳转,即从第二个页面往回跳,且传数据,需要在第一个页面(活动)中按钮的点击事件中添加如下代码,
除此之外,还要重写onActivityResult方法
但是这样写,会有问题如果不点按钮进行返回,就没法传数据了,例如我们平常的使用习惯是按Back键,解决的方法则是要在第二个活动中重写onBackPressed方法中,就是把原先第二个活动中按钮点击事件中的代码粘贴过来。
这样就ok了。
1.显示地使用Intent对象,跳转页面
//显示调用intent创建一个intent对象,构造方法传入两个参数,第一个跳转前的页面,第二个将要跳转到的页面 Intent intent = new Intent(MainActivity.this,SecondActivity.class); //startActivity方法进行页面跳转 startActivity(intent);
2.隐式地使用 Intent进行页面跳转
//隐式调用intent,方法里的参数AndroidMainifest.xml里的SecondActivity的action Intent intent = new Intent("com.example.MainActivity.ACTION_START"); //为intent添加一个category,intent就会找category匹配的活动(Activity) intent.addCategory("com.example.MainActivity.MY_CATEGORY");
这种方法,需要为所要跳转的第二个Activity在AndroidMainfests配置中添加action属性和category属性
<intent-filter> <action android:name="com.example.MainActivity.ACTION_START"/> <category android:name="android.intent.category.DEFAULT"/> //添加SecondActivity的category的声明 <category android:name="com.example.MainActivity.MY_CATEGORY"/> </intent-filter>
3.从第一个页面往第二个页面跳转,利用Intent对象的putExtra方法传数据,这个方法里的两个参数是一个键值对。
//页面传值 String data = "hello secondActivity"; intent.putExtra("extra_data",data); startActivity(intent);
4.从第二个页面跳往第一个页面,使用Intent传数据。下面是需要在第二个活动的按钮点击事件中,所需写的代码。
Intent intent1 = new Intent(); intent1.putExtra("data_return","Hello MainActivity"); setResult(RESULT_OK,intent1); finish();
这样的跳转,即从第二个页面往回跳,且传数据,需要在第一个页面(活动)中按钮的点击事件中添加如下代码,
Intent intent = new Intent(MainActivity.this,SecondActivity.class); startActivityForResult(intent,1);
除此之外,还要重写onActivityResult方法
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ case 1:if (resultCode == RESULT_OK) { String returnData = data.getStringExtra("data_return"); Toast.makeText(MainActivity.this,returnData,Toast.LENGTH_LONG).show(); } break; default: } }
但是这样写,会有问题如果不点按钮进行返回,就没法传数据了,例如我们平常的使用习惯是按Back键,解决的方法则是要在第二个活动中重写onBackPressed方法中,就是把原先第二个活动中按钮点击事件中的代码粘贴过来。
@Override //当按返回键的时候,调用这个方法 //重写这个方法 public void onBackPressed() { Intent intent1 = new Intent(); intent1.putExtra("data_return","Hello MainActivity"); setResult(RESULT_OK,intent1); finish(); }
这样就ok了。
相关文章推荐
- 简单方法实现Android阅读器分页
- ListView中EditText焦点获取
- 获取 ViewPager 内部子控件的方法
- Android之关于SD卡的读取问题
- Android自定义控件,画一条线
- 杂记3:android AsyncTask基础应用
- 安卓日记——保存你的日夜间模式
- ubuntu下不能识别安卓设备
- Android事件总线分发库的使用
- android monitor
- android群英传学习笔记-自定义ScrollView
- android zipalign
- android调试命令积累--getevent
- android lint
- 学习笔记之——Android状态栏微技巧,带你真正理解沉浸式模式
- 判断android中列表是否在顶部
- Android 通过java代码实现修改指定路径文件的读写权限。
- Android 动画基础总结
- Android开发之RecyclerView的使用全解
- Android 使用js调用Java