文章目录
参考书籍:第一行代码:Android(第二版)(郭霖):第二章
一、新活动创建(Activity)
1、介绍
活动是最容易吸引用户的地方,它是一种可以包含用户界面的组件,主要用于和用户进行交互。一个应用程序中可以包含零个或多个活动,但不包含任何活动的应用程序很少见
2、新建一个Android项目
1、New Project选择No Activity
2、填写以下信息
3、手动创建活动
在app/src/main/java/com.example.activitytest目录下创建一个叫FirstActivity文件,并不要勾选Generate Layout File 和Launcher Activity,如下图选择选项
解释:
勾选Generate Layout File 表示会自动为FirstActivity创建一个对应的布局文件
勾选Launcher Activity 表示会自动将FirstActivity设置为当前项目的主页
4、创建和加载布局
在app/src/main/res目录下创建一个文件夹叫layout
layout文件下新建一个文件叫first_layout文件,如下图选项
在布局中添加一个按钮(在右上角选择Text或者Code即可切换到代码部分)
<?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">
<!--@+id/id_name在xml中定义一个id
layout_width="match_parent"指定当前元素的宽度,match_parent表示和当前父元素一样宽
layout_height="wrap_content"表示当前元素的高度只要能刚好包含里面的内容即可
-->
<Button
android:id="@+id/button_1"
android:text="Button1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
5、加载布局
重新回到FirstActivity.java
package com.example.activitytest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//添加布局
setContentView(R.layout.first_layout);
}
}
6、AndroidManifest.xml文件中注册活动
打开app/src/main/AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.activitytest" >
<!--由于上面的package所以下面注册的时候只需要利用(.类名)格式,
活动的注册需要在application里面,通过activity标签来注册 -->
<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.ActivityTest" >
<!--android:name 表示需要注册的活动名字-->
<activity
android:name=".FirstActivity"
android:label="每个活动的标题栏"
android:exported="true">
<!-- 配置项目的开始页面 -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />