public class FirstActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
}
}
项目中的任何活动都应该重写Activity的onCreate()方法。
创建和加载布局文件
Android程序的设计讲究逻辑和视图分离,最好每一个活动都能对应一个布局,布局就是用来显示界面内容的;
新建布局文件:
res/layout目录下新建Android XML File first_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"
/>
setContentView(R.layout.first_layout);
setContentView()方法来给当前的活动加载一个布局,一般需要传入一个布局文件的id。前面提到过,只需要调用R.layout.first_layout就可以得到first_layout.xml布局的id,然后将它传入setContentView()即可。
注意:这里的R指的是项目包下的R文件。Android SDK还会自动提供一个android包下的R文件。
在AndroidManifest文件中注册
所有的活动必须在AndroidManifest.xml中进行注册才能生效。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.activitytest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
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>
</manifest>
.FirstActivity:表示com.example.activitytest.FirstActivity的缩写; 由于最外层的<manifest>标签中已经通过package属性指定了程序的包名,因此注册活动时这一部分可以省略。
android:label 指定活动中标题栏的内容,标题栏是显示在活动最顶部的。给活动指定的label不仅会成为标题栏中的内容,还会成为启动器中应用程序显示的名字。
<intent-filter>主活动声明