Android学习笔记--3.Intent的使用
来源:互联网 发布:淘宝店铺pc端装修视频 编辑:程序博客网 时间:2024/06/05 02:21
前言:今天学的是利用Intent对象进行页面的跳转,同时也利用Intent进行页面间的数据传递。
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了。
0 0
- Android学习笔记--3.Intent的使用
- Android学习笔记(4)-学习Intent的使用
- Android学习笔记(4)-学习Intent的使用
- Android学习笔记-学习Intent的使用
- Android学习笔记02——Intent的使用
- 隐式Intent的使用——Android学习笔记3
- Android学习笔记----使用Intent传递对象
- Android学习笔记:使用Intent切换活动
- Android学习笔记--Intent
- android学习笔记---Intent
- Android学习笔记 - Intent
- Adnroid学习笔记:Intent与<intent-filter>的使用
- 【Android学习笔记】Intent的基本作用
- 雾山的Android学习笔记---Intent
- 雾山的Android学习笔记---Intent
- Intent的用法 - Android学习笔记2
- Android学习笔记-Intent的显式隐式
- Android学习 - Intent使用
- & |运算小记
- Codeforces Round #332 (Div. 2)D. Spongebob and Squares
- 美团笔试题(JavaScript)
- java虚拟机垃圾回收
- lightoj-1008 - Fibsieve`s Fantabulous Birthday【思维】【找规律】
- Android学习笔记--3.Intent的使用
- java.lang.UnsatisfiedLinkError: com.android.tools.fd.runtime.IncrementalClassLoader$DelegateClassLoa
- Lightoj 1138 ( Trailing Zeroes (III))
- JavaEE完整技术体系文章陆续上映!!!
- Qt 延时
- 求乘方取模(快速幂+慢速乘法模板)
- [noip模拟赛]旅行Pod(spfa)
- 图的深度遍历
- Android 之 EditText ImageView ImageButton控件