当前位置: 移动技术网 > IT编程>移动开发>Android > Android基础Activity篇——创建一个活动(Activity)

Android基础Activity篇——创建一个活动(Activity)

2018年04月17日  | 移动技术网IT编程  | 我要评论

文章开讲啦,适合婚礼上唱的歌,你要高雅 郭德纲

1.创建活动

  首先用AS创建一个add no activity项目名使用ActivityTest,包名为默认的com.example.activitytest

2.右击app.java.com.example.activitytest包,new-->Activity-->Empty Activity,将活动命名为FirstActivity,不勾选Generate(生成) Layout和Launcher Activity选项。

  其中Layout是布局用的,而Launcher Activity是用于将当前活动设置为Main活动

3.打开刚才创建的FirstActivity.java,可以看到AS已经自动重写了onCreate()方法。

public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
   }
}

  需注意的是项目中的任何活动都应该重写该方法。从super可以看出这里的onCreate()是直接调用的父类的方法。

4.创建布局

  在res目录右击,new-->Directory(目录),创建layout目录。右击layout-->Layout resource file,创建布局文件first_layout.xml,根元素默认为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>

  其中自己添加的代码是<Button />标签部分,

  android:id="@+id/button_1"是用来给当前元素定义一个唯一的标识符。(在Xml代码中@id/id_name表示引用一个id,而@+id/id_name表示创建一个id)。

  后面的width,height当然就是用来设定当前元素的宽高的,match_parent(匹配_父元素),wrap_content(包_内容)。

  android:text="Button 1"用来显示按钮的内容的。

5.加载布局

  要将布局加载到活动中才能显示,所以需在活动的onCreate()方法中写入如下代码。

setContentView(R.layout.first_layout);

  setContentView(设置内容外观),任何资源文件都会在R文件中生成一个相应的id,而这里直接传入之前所创建的布局文件id(在java代码中引用id的格式为R.路径名.文件名

6.注册活动

  项目中所有活动都需要在AndroidMainfest.xml中注册

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.l.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" android:label="this is first activity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

  注册是在<activity>标签中进行的,

  android:name是用来指定注册哪一个活动的,而这里的“.FirstActivity”使用的是相对路径(因为mainfest中的package中已经声明了活动所在的包名)。

  android:label中写的是活动标题栏中的内容。

  <intent-filter>(目的-过滤)中需添加以下两句

 <action android:name="android.intent.action.MAIN"/>
 <category android:name="android.intent.category.LAUNCHER"/>

  第一句表示将此活动设置为主方法,第二句表示应用启动时就执行该活动。category(种类)。

6.运行

  运行结果如下

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网