今天我们来聊一聊关于Android之中的活动(Activity)。
活动是什么呢?活动是最容易吸引用户的地方。这个活动啊,是一种可以包含用户界面的 组件,主要用于和用户进行交互。一个应用程序中可以包含零个或多个活动,但不包含任何活动的应用很少见——毕竟想必谁也不想让自己的应用永远无法被用户看到吧?
活动有什么基本用法呢?首先的话,是由Android Studio自动帮我们完成的——再FirstActivity中已经重写了这个方法,代码如下图所示:
public class FirstActivity extends AppCompatActivity { @override protected void onCreate(Bundle save dInstanceState) { super.onCreate(savedInstanceState); } }
可以看到,onCreate()方法非常简单,就是调用了父类的onCreate()方法。当然,这只是默认的实现,后面我们还需要在里面加入很多自己的逻辑。
之后就是创建和加载布局了。
Android程序的设计讲究逻辑和视图分离,最好每一个活动都能对应一个布局,布局就是用来显示页面内容的,因此我们现在就可以手动的创建一个布局文件了。
代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
由于我们刚才在创建布局文件时选择了LinearLayout作为根元素,因此现在布局文件中已经有一个LinearLayout元素了。那我们现在对这个布局稍做编辑,添加一个按钮,如下所示:
<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>
这里添加了一个Button元素,并在Button元素的内部增加了几个属性。android:id是给当前元素定义一个唯一标识符,之后可以在代码中对这个元素进行操作。可能会对@+id/button_1这种语法感到陌生,但如果把加号去掉,变成@id/button_1,这样子的话,瞬间就会感到十分熟悉了。