1.在创建了第一个活动之后,你需要知道,项目中的任何活动都应该重写Activity的onCreate()方法,
public class FirstActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
可以看到,onCreate方法非常简单,就是调用了父类的onCreate方法。当然这只是默认的实现,后面还需要我们在里面加入很多自己的逻辑。
2.在布局文件中以linearLayout作为根元素时,在里面添加一个Button按钮,并在Button元素的内部添加了一个属性。android:id是给当前的元素定义一个唯一标识符,之后可以在代码中对这个元素进行操作。
如果你需要在一个XML中引用一个id,就是用@id/id_name这种语法,而如果你需要在XML中定义一个id,则要使用@+id/id_name这种语法。
随后android:layout_width指定了当前元素的宽度。这里使用match_parent表示让当前元素和父元素一样宽。
android:layout_height指定了当前元素的高度,这里使用了wrap_content表示当前元素的高度只要能刚好包含里面的内容就行。
android:text指定了元素中显示的文字内容。
<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>
重点:所有的活动都需要在AndroidManifest.xml中进行注册才能生效!
<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:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".FirstActivity"></activity> </application> </manifest>
但是,仅仅是这样注册了活动,程序仍然是不能运行的,因为还没有为程序配置主活动,也就是说,当程序运行起来的时候,不知道要首先启动哪个活动。配置主活动的方法其实就是在<Activity>标签的内部添加<intent-filter>标签,并且在这个标签中添加
<action android:name="android.intent.action.MAIN"/>和
<category android:name="android.intent.category.LAUNCHER"/>这两句声明即可。
除此之外,我们还可以使用android:label 指定活动中标题栏的内容,标题栏是显示在活动
最顶部的,待会儿运行的时候你就会看到。需要注意的是,给主活动指定的label不仅会成为标题栏中的内容,还会成为启动器(Launcher)中应用程序显示的名称。<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.activitytest"> <application ... > <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>