创建和加载布局
Android程序的设计讲究逻辑和视图分离,最好每一个活动都能对应一个布局,布局就是用来显示界面内容的,因此我们需要创建一个布局文件。
右击app/src/main/res →New→Directory,新建一个名为layout的目录。然后右击此目录→Layout resource file,新建一个名为first_layout,根元素就默认好了。
就会出现as为我们提供的可视化布局编辑器,下方有两个tab(当前为Design),我们切换到Text就可以看到使用XML文件的方式来编辑布局的。
由于我们默认使用LinearLayout作为根元素,因此现在布局文件已经有一个LinearLayout元素了。我们尝试添加一个按钮
<?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"
/>
</LinearLayout>
- android:id是给当前的元素定义一个唯一标识符,其中@+id/id_name为定义一个id,@id/id_name为引用资源
- android:layout_width指定了当前元素的宽度,match_parent表示让当前元素和父元素一样宽
- android:layout_height指定了当前元素的高度,wrap_content表示当前元素的高度只要能刚好包含里面的内容就行
这时我们可以点击右侧的Preview进行预览
回到FirstActivity,在onCreate()方法中加入一行代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
}
这里调用了setContentView()方法来给当前的活动加载一个布局,而在setContentView()方法中,我们一般都会传入一个布局文件的id。项目中添加的任何资源都会在R文件中生成一个相应的资源id,所以只需调用R.layout.first_layout就可以得到first_layout.xml布局的id。
在AndroidManifest文件中注册
所有的活动都要在AndroidManifest.xml中进行注册才能生效,而实际上as已经将FirstActivity注册了
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.activitytest">
<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/AppTheme">
<activity android:name=".FirstActivity"></activity>
</application>
</manifest>
活动的注册声明要放在application标签内,通过activity标签来对活动进行注册。
android:name来指定具体注册哪一个活动,.FirstActivity其实是com.example.activitytest.FirstActivity的缩写,因为最外层manifest标签中通过package属性指定了程序的包名。
不过这样还是不能运行的,因为还没有配置主活动(程序运行起来的时候首先运行的活动)。需要在activity标签的内部加入intent-filter标签,并在这个标签里添加<action android:name="android.itent.action.MAIN"/>
和<category android:name="android.itent.category.LAUNCHER"/>
这两句声明即可。还可以使用android:label指定活动中标题的内容,标题栏是显示在活动最顶部的。需要注意的是,这个label还会成为启动器(Launcher)中应用程序显示的名称。
<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/AppTheme">
<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>
然后我们就可以运行了,结果如下:
如果应用程序中没有声明任何一个活动作为主活动,这个程序仍然是可以安装的,只是你无法在启动器中看到或者打开这个程序。这种程序一般都是作为第三方服务供其它应用在内部进行调用的,如支付宝快捷支付服务。
总结:
- 活动与布局文件之间的关系,活动中在onCreate方法中调用setContentView加载布局文件
- 每个应用程序需要配置一个主程序作为首先启动的活动,每个活动都需要在AndroidManifest.xml文件中进行注册及配置
- 了解布局文件xml的基本写法(相对来说不重要)