zoukankan      html  css  js  c++  java
  • intent初步解析

    使用Intent穿梭活动
    显式Intent
    一个Activity太单薄了,作为一个秃头 的程序猿,我们应该高级一点
    我们再创建一个活动,命名为SecondActivity:File-New-Activity-Empty Activity
    我们就获得了第二个活动
    编辑layout目录下的activity-main.xml,替换成以下代码

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
    android:id="@+id/button_1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button1">
    </Button>


    </LinearLayout>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <Button代表一个按钮,其他的我们在之后会讲
    接着我们在MainActivity里添加以下代码

    Button button1=findViewById(R.id.button_1);
    button1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Intent intent=new Intent(MainActivity.this,SecondActivity.class);
    startActivity(intent);
    }
    });
    1
    2
    3
    4
    5
    6
    7
    8
    findViewById()方法用于获取在布局文件中定义的元素,button_1正是通过android:id="@+id/button_1"这样指定的。
    然后我们通过调用setOnClickListener()方法为按钮注册一个监听器,点击按钮时即会执行onClick方法。
    Intent有多个构造函数的重载,这是其中一个。这个构造函数接收两个参数,第一个为Context要求启动活动的上下文,第二个class则是指定想要启动活动的目标。建立完后通过调用startActivity()方法就可以启动活动了,其接收一个Intent参数,我们将构建好的Intent传进去就行了。
    然后运行,就可以跳转活动了!

    隐式Intent
    相较于显式,隐式Intent更智能了一点,我们可以通过指定更为抽象的action和category信息,然后让系统帮我们去找要启动哪个活动。
    action:一个字符串,指明了当前活动可以响应这个字符串
    category:指明当前活动的环境
    只有action和category同时匹配时,这个活动才能响应Intent
    我们先打开AndroidManifest.xml,找到SecondActivity,添加如下代码

    <activity android:name=".SecondActivity">
    <intent-filter>
    <action android:name="Start"/>
    <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
    </activity>
    1
    2
    3
    4
    5
    6
    这里我们就指定了SecondActivity的action为"Start",category为"android.intent.category.DEFAULT"。
    进入MainActivity,修改onClick里的内容像这样

    public void onClick(View v) {
    Intent intent=new Intent("Start");
    startActivity(intent);
    }
    1
    2
    3
    4
    我们同样可以进入第二个活动

  • 相关阅读:
    android 学习
    android 学习
    阅读笔记《人月神话》1
    android 学习
    android 学习
    android 学习
    android 学习
    android 学习(家庭记账本的开发 6)
    每日日报
    每日日报
  • 原文地址:https://www.cnblogs.com/hyhy904/p/11667857.html
Copyright © 2011-2022 走看看