07 活动
活动(Activity)
-
是最容易吸引用户的地方
-
是一种可以包含用户界面的组件
作用
用于和用户进行交互
活动的基本用法
STEP 1 :创建新项目,选择Add noActivity
STEP 2 :手动创建活动
-
勾选Generate Layout File表示会自动为FirstActivity创建一个对应的布局文件
-
勾选Launcher Activity表示会自动讲FirstActivity设置为当前项目的主活动
STEP 3 : 创建和加载布局
选中res目录右键
在项目中,任何活动都应该重写Activity的onCreate()方法,我们在FirstActivity中已经重写了这个方法,是由Android studio自动帮我们完成的
FirstActivity.java
package com.example.myactivitytest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class FirstActivity extends AppCompatActivity {
/*
项目中的任何活动都需要重写Activity的onCreate()方法
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
调用setContentView()方法给当前活动加载布局
传入参数为布局文件的id
项目中添加的任何资源都会在R文件中生成一个相应的资源id
我们把创建的first_layout.xml布局的id已经添加到了R文件中
Resource:资源
所有的活动在AndroidManifest.xml中注册才能生效
Android studio可以帮我们自动在xml中注册
*/
setContentView(R.layout.first_layout);
}
}
first_layout
添加了一个Button元素,并在Button元素的内部增加了几个属性
<?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="Button 1"
/>
<!--
id:给当前元素定义一个唯一标识符
layout_width:当前元素的宽度
match_parent:当前元素宽度和父元素一样宽
layout_height:当前元素的高度
wrap_content:当前元素的高度刚好包含里面的内容就行
text:指定元素中显示的内容
-->
</LinearLayout>
STEP 4:在AndroidManifest.xml中注册
- 所有的活动在AndroidManifest.xml中注册才能生效
- Android studio可以帮我们自动在xml中注册
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myactivitytest">
<!-- android:label,指定活动中标题栏的内容 -->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyActivityTest">
<!--
活动的声明要放在<application>标签内
通过<activity>标签来进行注册
android:name指定具体注册哪一个活动
.FirstActivity是com.example.myactivitytest.FirstActivity的缩写
在manifest时,已经指定了包名,所以在注册活动这一部分,可以直接使用.FirstActivity
<intent-filter>标签中的两个标签是为程序配置主活动
-->
<activity android:name=".FirstActivity"
android:label="This is FirstActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
如果应用程序中没有声明任何一个活动作为主活动,这个程序仍然是可以正常安装的,
只是你无法在启动器中看到或者打开这个程序
这种程序一般是作为第三方服务供其他应用在内部进行调用的
例如:支付宝快捷支付功能
运行程序