未分类

Android第二课——构建简单的应用

编写应用

一个最简单的app

主代码

1
2
3
4
5
6
7
8
public class HelloWorldActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hello_world_layout);
//R类是自动生成的,包含所有res目录下资源的id
}
}
  • AppCompatActivity是一种向下兼容的Activity,是Activity的子类。Activity是Android系统提供的一个活动基类,所有活动必须继承它或它的子类才拥有活动的特性。
  • onCreate()方法是创建活动时必定会执行的方法。
  • setContentView()方法为当前活动引入布局。Android程序的设计讲究逻辑与视图分离,因此常在布局文件中编写界面,然后在活动中引入。
  • 使用finish()方法销毁活动。

layout文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/hello_world_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.helloworld.HelloWorldActivity">
<Button
android:id="@+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"
/>
<!--引用id用@id/name语法,定义id用@+id/name语法->
<!--TextView为文本-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>

资源——字符串

1
2
3
<resources> 
<string name="app_name">HelloWorld</string>
</resources>
引用资源的方式
  • 代码中:通过R.string.app_name引用该字符串。
  • XML中:通过@string/app_name引用该字符串。\
    其中string部分可替换成需要引用的资源类型,如layout,drawable等。例见AndroidManifest.xml文件。
分享到