什么是Intent
Intent可以理解为信使(意图)
由Intent来协作完成Android各个组件之间的通讯, 也可以说是实现页面与页面之间的跳转
Intent实现页面之间的跳转
- startActivity(intent) //第一种方式启动
-
startActivityForResult(intent, requestCode); //第二种启动方式
onActivityResult(int requestCode, int resultCode, Intent data)
setResult(resultCode, data);
第一种启动方式实现直接跳转,无返回值
第二种启动方式A页面->B页面, B页面也能回传到A页面数据
onActivityResult(int requestCode, int resultCode, Intent data)
这个是 用来A页面接收B页面回传的数据用的
setResult(resultCode, data) 这个是用来B页面回传给A页面数据
首先创建一个项目
新建两个Activity
然后再layout 里面新建两个页面布局 layout右键ànewàAndroid XML File
随后,进行绑定,例如:
然后,配置清单文件AndroidManifest.xml
然后,在activity_first 插入两个button 一个textview 分别用来第一个和第二个跳转方式, 以及数据回传,代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <Button 8 android:id="@+id/bt_first" 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" 11 android:text="第一种启动方式" /> 12 13 <Button 14 android:id="@+id/bt_Second" 15 android:layout_width="match_parent" 16 android:layout_height="wrap_content" 17 android:text="第二种启动方式" /> 18 19 <TextView 20 android:id="@+id/textview" 21 android:layout_width="match_parent" 22 android:layout_height="wrap_content" 23 android:text="把第二个页面回传的数据显示" /> 24 25 </LinearLayout>
刚才提到了,实现跳转需要用到Intent意图,代码很简单 清晰明了 我直接贴代码了
首先 FirstActivity
1 package com.example.intentdemo; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.widget.Button; 9 import android.widget.TextView; 10 11 public class FirstActivity extends Activity { 12 Button bt_first, bt_second; 13 TextView textView; 14 15 @Override 16 protected void onCreate(Bundle savedInstanceState) { 17 super.onCreate(savedInstanceState); 18 setContentView(R.layout.activity_first); 19 20 initView(); 21 } 22 23 private void initView() { 24 // 关联控件 25 bt_first = (Button) findViewById(R.id.bt_first); 26 bt_second = (Button) findViewById(R.id.bt_Second); 27 textView = (TextView) findViewById(R.id.textview); 28 bt_first.setOnClickListener(new OnClickListener() { 29 30 @Override 31 public void onClick(View arg0) { 32 // 第一种跳转,无数据返回跳转 33 Intent intent = new Intent(FirstActivity.this, 34 SecondActivity.class); 35 intent.putExtra("content", "第一种跳转方式"); 36 startActivity(intent); 37 } 38 }); 39 bt_second.setOnClickListener(new OnClickListener() { 40 41 @Override 42 public void onClick(View arg0) { 43 // 第二种方式,有数据返回跳转 44 Intent intent = new Intent(FirstActivity.this, 45 SecondActivity.class); 46 intent.putExtra("content", "第二种跳转方式"); 47