安卓基础知识回顾-----Intent的使用

时间:2022-12-07 15:32:47

Intent的使用

1、Activity之间的切换通过Intent来完成。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.luxh.intent" android:versionCode="1" android:versionName="1.0" >

    <uses-sdk  android:minSdkVersion="11" android:targetSdkVersion="18" />

    <application  android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
        <!-- 第一个Activity -->
        <activity  android:name="cn.luxh.intent.FirstActivity" android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- 第二个Activity -->
        <activity  android:name="cn.luxh.intent.SecondActivity" android:label="@string/second_activity">
                <intent-filter>
                       <action android:name="cn.luxh.intent.SecondActivity"/> <!--意图筛选器名称 -->
                       <category android:name="android.intent.category.DEFAULT"/><!--意图筛选器类别 -->
                </intent-filter>
        </activity>
    </application>

</manifest>
package cn.luxh.intent;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;

public class FirstActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        handleBtnJumpClick();
    }

    /** * 处理按钮点击事件 */
    private void handleBtnJumpClick() {
        Button btn_jump = (Button) findViewById(R.id.btn_jump);
        btn_jump.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建一个Intent

                /*Intent intent = new Intent(); intent.setClass(FirstActivity.this, SecondActivity.class);*/

                //通过意图筛选器名称创建Intent
                Intent intent = new Intent("cn.luxh.intent.SecondActivity");

                //启动新的Activity
                startActivity(intent);
            }
        });
    }

}
package cn.luxh.intent;

import android.app.Activity;
import android.os.Bundle;

public class SecondActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }
}