Intent的使用
Intent定义
Intent是一种在不同组件之间传递的请求消息,是应用程序发出的请求和意图。作为一个完整的消息传递机制,Intent不仅需要发送端,还需要接收端。
Intent存在显性与隐性的区别
显式Intent定义:对于明确指出了目标组件名称的Intent,我们称之为显式Intent。
隐式Intent定义:对于没有明确指出目标组件名称的Intent,则称之为隐式Intent。
二.使用显性Intent实现两个Activity跳转
MainActivity的xml
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="跳转" />
</LinearLayout>
MainActivity2的xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.a22120.myapplication.Main2Activity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="helloworld"
/>
</LinearLayout>
MainActivity
package com.example.a22120.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(getApplicationContext(), Main2Activity.class);
intent.putExtra("name", "001");
startActivity(intent);
}
});
}
}
MainActivity2中不做修改即可
效果如下:
点击按钮跳转至MainActivity2