04 |「Activity 和 Intent」

这篇具有很好参考价值的文章主要介绍了04 |「Activity 和 Intent」。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

学习 Activity、Intent、Context

一、Activity

1、继承关系

java.lang.Objectandroid.content.Contextandroid.content.ContextWrapperandroid.view.ContextThemeWrapperandroid.app.Activity
  • Activity继承自ContextThemeWrapper,可以设置主题。
  • ContextThemeWrapper继承自ContextWrapper,封装了Context的常用功能。
  • ContextWrapper继承自Context,即Activity本质上是一个Context。
  • Context定义了与Android环境交互的接口。
  • 最终都继承自java.lang.Object。
  • 通过这种继承,Activity就集成了Context的能力,可以访问资源、数据库、SharedPreferences等。
    同时作为Context的子类,Activity也可以作为Context参数被传递使用。
    这种继承关系让Activity既是一个 UI 组件,也是一个Context,很好地结合了两者的功能

2、简介

  • Activity 代表应用程序的单个屏幕,用户可以使用该屏幕执行单一、集中的任务,Activity 通常以全屏窗口的形式呈现给用户;
  • Activity 是一个应用程序组件,单个用户任务的单个屏幕;
  • 每个 Activity 都有自己的布局文件;
  • 可以为 Activity 分配父子关系,以在应用程序中启用向上导航;
  • 一个应用程序通常由多个彼此松散的屏幕组成。每个屏幕都是一个 Activity;
  • 应用程序中有一个主Activity(MainActivity.java),在应用程序启动时呈现给用户;通过主Activity 可以启动其他 Activity 来执行不同的操作;
  • 每次启动新活动,前一个 Activity 都会停止,但系统会将该 Activity 保留在堆栈中;当新 Activity 启动时,该新 Activity 被推入后台堆栈并获取用户焦点;当用户完成当前 Activity 并按下后退按钮时,该 Activity 将从堆栈中弹出并销毁,并恢复上一个 Activity;
  • Activity 是有意图地开始或激活的。Intent 是一条异步消息,可以在 Activity 中使用它来请求来自另一个 Activity 或某个其他应用程序组件的操作;可以使用 Intent 从一个 Activity 启动另一个 Activity,并在 Activity 之前传递数据;

二、Intent

  • 允许从应用程序中的另一个组件请求操作。例如,从另一个组件启动一个 Activity;
  • 显示 Intent:可以指示接收数据的特定目标组件;
  • Intent 附加信息是 Bundle,键值对;

三、Context

  • 全局信息:应用程序的资源,图片资源、字符串资源 ;
  • 作用:用来访问全局信息,一些常用的组件(Activity、Service)继承自 Context(继承后具有访问全局资源的能力),目的是通过 Context 方便地访问资源;
  • setText 的实现:getContext():获取相关的 Context 对象,getResource():获取资源管理器,getText(id):返回资源 id 的字符串;
    // 访问字符串资源
    public class MainActivity extends AppCompatActivity {
        private TextView tv;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            tv = new TextView(this);  // this:MainActivity的实例,将this传给context,在内部对context有一个引用
            tv.setText(R.string.hello_world); 
            setContentView(tv);  // 指定一个视图
            }
    }
    
    // 访问图片资源
    public class MainActivity extends AppCompatActivity {
      
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
           	ImageView iv = new ImageView(this);
           	iv.setImageResource(R.mipmap.ic_launcher);
            }
    }
    

四、实践 Lab

1、需求

  • 创建并构建两个 Activity(Activity1Activity2);
  • Activity1 作为主 Activity,主要包含一个 “发送” 按钮,当用户点击此按钮将使用 Intent 来启动 Activity2
04 |「Activity 和 Intent」,安卓开发入门指南(注重实操),android
  • 主 Activity 中添加 EditText,用户输入消息,并点击发送按钮,主 Activity 使用 Intent 来启动第二个 Activity 并将用户的消息发送到第二个 Activity,第二个 Activity 显示它接收到的消息
04 |「Activity 和 Intent」,安卓开发入门指南(注重实操),android
  • 第二个 Activity 添加 EditText 和回复按钮;用户键入回复消息并点击回复按钮,使用 Intent 将回复消息从第二个 Activity 传递给主 Activity,并显示;
04 |「Activity 和 Intent」,安卓开发入门指南(注重实操),android

2、代码实现

  • 创建第一个Activity 布局
// activity_main.xml(主Activity)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="16dp"
        android:textColor="@android:color/background_dark"
        android:layout_marginBottom="16dp"
        android:onClick="launchSecondActivity"
        android:text="@string/button_main" />

    <EditText
        android:id="@+id/editText_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginBottom="19dp"
        android:ems="10"
        android:inputType="text"
        android:text="Name" />
</RelativeLayout>
  • 创建第二个Activity 布局
// 第二个Activity
<androidx.constraintlayout.widget.ConstraintLayout 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=".SecondActivity">

    <TextView
        android:id="@+id/text_header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:text="@string/text_header"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/text_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="60dp"
        android:layout_marginTop="40dp"
        android:text=""
        android:textAppearance="AppCompat.Medium"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text_header" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • 主 Activity 添加 Intent
   public void launchSecondActivity(View view) {
        // 将显示Intent添加到主Activity,Intent用于单击发送按钮时激活第二个Activity
        // 参数:第一个参数,应用程序Context;第二个参数:将接收该Intent的特定组件
        // 当点击发送按钮时,MainActivity发送Intent并启动第二个Activity 出现在屏幕
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }
}
  • 从主 Activity 发送数据到第二个 Activity
    • 使用 Intent 将数据从一个 Activity 发送到另一个 Activity
    • Intent 传递数据到目标 Activity 的方式
      • 1)数据字段:Intent 数据指要操作的特定数据的 URl
      • 2)Intent 附加信息,如果传递的数据不是 URl 或想要发送多条信息,可以将附加信息放入extras 中。
      • Intent 附加信息内容是 Bundle 。Bundle 是数据集合,存储形式为键值对
      • 从一个 Activity 传递信息到另一个 Activity,可以将键和值放入发送 Activity 的 Intent extra 中,然后在接收 Activity 中将它们取出;

Bundle 中包含其他数据,本需求中为用户输入的字符串文章来源地址https://www.toymoban.com/news/detail-623455.html

public class MainActivity extends AppCompatActivity {
    private static final String LOG_TAG = MainActivity.class.getSimpleName();
    public static final String EXTRA_MESSAGE = "com.example.myapplication.extra.MESSAGE";
    private EditText mMessageEditText;
    public static final int TEXT_REQUEST = 1;  // 第二个Activity回复响应的键
    private TextView mReplyHeadTextView;  // 回复标头Textview
    private TextView mReplyTextView;  // 回复TextView元素


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);  // 指定一个视图
        mMessageEditText = findViewById(R.id.editText_main);  // 使用findViewById()获取对 EditText 的引用
        mReplyHeadTextView = findViewById(R.id.text_header_reply);
        mReplyTextView = findViewById(R.id.text_message_reply);
        }


    public void launchSecondActivity(View view) {
        // 将显示Intent添加到主Activity,Intent用于单击发送按钮时激活第二个Activity
        // 参数1:应用程序Context和将接收该Intent的特定组件
        // 当点击发送按钮时,MainActivity发送Intent并启动第二个Activity 出现在屏幕
        Intent intent = new Intent(this, SecondActivity.class);
        String message = mMessageEditText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivityForResult(intent, TEXT_REQUEST);

    }

    @Override
    // 回调方法
    // requestCode:请求
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 处理返回数据
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TEXT_REQUEST) {
            if (requestCode == RESULT_OK) {
                String reply =
                        data.getStringExtra(SecondActivity.EXTRA_REPLY);
                mReplyHeadTextView.setVisibility(View.VISIBLE);
                mReplyTextView.setText(reply);
                mReplyTextView.setVisibility(View.VISIBLE);
            }
        }
    }
}
  • 将数据从第二个 Activity 返回给主 Activity
    startActivity():使用显式 Intent 启动另一个 Activity 时,不会期望返回任何数据,只是激活该 Activity;
    如果想从激活的 Activity 中获取数据,则需要以 startActivityForResult() 启动它
public class SecondActivity extends AppCompatActivity {
    public static final String EXTRA_REPLY = "com.example.myapplication.extra.REPLY";
    private EditText mReply;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        mReply = findViewById(R.id.editText_second);
        // 获取激活此Activit的Intent
        Intent intent = getIntent();
        // 获取Intent extra中包含的字符串
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        // 获取要显示的控件的引用
        TextView textView = findViewById(R.id.text_message);
        // 通过引用在此控件上显示获取Intent extra中包含的字符串
        textView.setText(message);
    }

    public void returnReply(View view) {
        String reply = mReply.getText().toString();
        Intent replyIntent = new Intent();
        replyIntent.putExtra(EXTRA_REPLY, reply);
        setResult(RESULT_OK, replyIntent);
        finish();
    }
}

到了这里,关于04 |「Activity 和 Intent」的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Android kotlin系列讲解(入门篇)使用Intent在Activity之间穿梭

    返回总目录 上一篇: Android kotlin系列讲解(入门篇)Activity的理解与基本用法        你应该已经对创建 Activity 的流程比较熟悉了,那我现在在 ActivityTest 项目再快速地创建一个 Activity 。        还是右击 com.example.activitytest 包→ New → Activity → Empty Views Activity ,会弹出

    2024年02月12日
    浏览(30)
  • ERC-3525 开发入门指南

    ERC-3525 标准是以太坊社区批准通过的半匀质化通证(Semifungible Token, 亦称为半同质化通证,简称 SFT)标准,由 Solv Protocol 提出。 ERC-3525 标准定义了一类新型的数字资产,具有以下突出优势: 与 ERC-721 标准兼容,具有唯一 ID 和可视化外观,可复用现有的大量 NFT 基础设施; 可

    2023年04月16日
    浏览(30)
  • 【Android 从入门到出门】第一章:Android开发技能入门指南

    🤵‍♂️ 个人主页:@艾迦洼的个人主页 ✍🏻作者简介:后端程序猿 😄 希望大家多多支持,如果文章对你有帮助的话,欢迎 💬👍🏻📂 目录 👋 第一章:Android开发技能入门指南 ⚽️ 1. 技术要求 ⚽️ 2. 使用变量和习惯用法在Kotlin中编写第一个程序 ⚾️ 2.1 准备 ⚾️

    2024年02月06日
    浏览(43)
  • 前端桌面应用开发实践:Electron入门指南

    随着互联网的快速发展,前端开发不再局限于网页应用,而是逐渐涉及到桌面应用的开发。Electron作为一种流行的前端桌面应用开发框架,为开发者提供了一种快速构建跨平台桌面应用的方式。本文将介绍Electron的基本概念和使用方法,并通过一个简单的示例来说明其开发实践

    2024年02月11日
    浏览(42)
  • HarmonyOS云开发基础认证题目记录——包括第一期:Serverless基础、第二期:快速构建用户认证系统、第三期:云函数入门指南、第四期:云数据库入门指南、第五期:云存储入门指南。

    1. 【判断题】  应用架构的演进依次经历了微服务架构、单体架构、Serverless架构等阶段。 错误 2. 【判断题】  认证服务手机号码登录需要填写国家码。 正确 3. 【判断题】  认证服务在绑定微信账号后就不能再绑定QQ账号了。 错误 4. 【判断题】  云函数可以根据函数的实际

    2024年02月05日
    浏览(73)
  • 【Rust指南】快速入门|开发环境|hello world

      本篇博客是Rust语言系列的开篇之作,以后有关Rust语言的文章也都会收录在我的 《进军Rust》 专栏里,我会精心打造这个专栏,帮助大家快速入门Rust语言,享受Rust语言带来的编程乐趣。虽然Rust相比其他语言入门慢,但这恰巧说明了Rust语言的特色——安全高效。对Rust语言

    2024年02月15日
    浏览(33)
  • PyCharm入门级使用指南,Python开发必备!

    PyCharm是一个专业的Python IDE,可以提供全面的Python开发支持,包括代码编辑、调试、测试、版本控制等功能。对于初学者来说,PyCharm可能会有点吓人,但是随着您的熟练使用,会发现它是一个非常强大且易于使用的工具。在本文中,我将向您介绍PyCharm的一些入门级使用方法。

    2024年02月16日
    浏览(43)
  • 热门Java开发工具IDEA入门指南——插件安装方式

    IntelliJ IDEA,是java编程语言开发的集成环境。IntelliJ在业界被公认为最好的java开发工具,尤其在智能代码助手、代码自动提示、重构、JavaEE支持、各类版本工具(git、svn等)、JUnit、CVS整合、代码分析、 创新的GUI设计等方面的功能是非常强大的。 本文给大家讲解在使用IntelliJ I

    2024年02月09日
    浏览(45)
  • 如何入门微信小程序开发,超详细学习指南大全

    2017年微信小程序发布开始,我就开始接触和学习微信小程序,看着小程序不断的更新迭代,功能越来越丰富,生态也越来越健全完善。 在这过程中,开发过商城小程序、停车扫码计费小程序、工具打卡小程序、流量主小程序等等。 很多人问我小程序怎么开发,一个人怎么制

    2024年02月09日
    浏览(46)
  • C++界面开发框架Qt 6.x入门指南 - 拥有程序主窗口

    Qt技术交流群:166830288      欢迎一起进群讨论 点击获取Qt组件下载 Qt Widget 是桌面环境中典型的用户界面元素,这些小部件很好地集成到底层平台,在 Windows、Linux 和 macOS 上提供原生外观。 这些小部件成熟且具有丰富的用户界面元素,适用于大多数传统用户界面。 与 

    2024年02月05日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包