显式Intent

来源:互联网 发布:祛痘产品淘宝 编辑:程序博客网 时间:2024/06/07 07:08

新建一个工程,取名为FirstActivity,layout文件取名为first_layout

1.将first_layout.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:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/button_1"        android:text="Button 1"/></LinearLayout>

2.右击app/src/main/java/com.example.activitytest->New->Activity->Empty Activity,输入类名为SecondActivity,layout名为second_layout.

3.将second_layout.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:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/button_2"        android:text="Button 2"/></LinearLayout>

4.在onCreate方法中设置一个按键监听,显式启动一个活动

package com.example.activitytest;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;public class FirstActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.first_layout);        //通过id找到按键控件对象        Button button1 = (Button) findViewById(R.id.button_1);        //设置按键点击事件        button1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                // 显式Intent                Intent intent = new Intent(FirstActivity.this,SecondActivity.class);                //启动SecondActivity活动                startActivity(intent);            }        });    }}

5. Intent构造函数传入了两个参数,第一个参数Context为启动活动的上下文,第二个参数Class为启动的目标活动,显性地指定了要启动的是哪一个

活动,因此叫显式活动,最后调用startActivity方法将intent构建的活动启动起来。















原创粉丝点击