第一行代码 开始创建一个activity

来源:互联网 发布:淘宝运营课程 编辑:程序博客网 时间:2024/05/16 12:28
xxxx.java
public class FirstActivity2 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);    //调用R.layout.first_layout获得first_layout.xml布局的id,传入setContentView中            2在活动中加载布局
}                                                 //setContentView方法为当前的活动加载一个布局

}
xxxx_layout.xml

<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"             //当前元素定义唯一标识符                                                                1编写布局

            android:layout_height="wrap_content"   //当前元素元素高度包住内容就好(wrap_content)(wrap缠绕,包)
            android:layout_width="match_parent"    //让当前元素与父元素一样宽 
            android:text="Button1"/>
</LinearLayout>
XML中引用资源的方法@id/id_name

标准方式
布局文件中
android:text="@string/button_1"
resource->value->string.XML
<string name="button_1">Hey girl,what`s your name?</string>

gen中R文件,在项目中添加任何资源都会在R文件中生成一个相应的资源ID,first_layout.xml布局文件ID已经添加到R文件中了
3.所有活动必须在AndroidManifest.xml中注册才能生效
     <activity>标签对活动进行注册声明,放在<application>标签内

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.administrator.activitytest2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".FirstActivity2" //activity指定注册哪一个活动,.FirstActivity2是缩写,外层manifest已经指定package,前面可省略
          android:label="This is FirstActivity2">//指定活动中标题栏内容,位于活动最顶端。给主活动指定的label,还会成为启动器(Launcher)中应用程序显示的名称
            <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>  //点击桌面应用程序图标首先出现的活动(主活动)必备两条
                 <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>>
        </activity>
    </application>

</manifest>
应用程序未声明任一个活动为主活动是,程序仍可正常安装,只是无法在启动器中看到或打开这个程序。这种程序一般作为第三方服务供其他应用在内部调用,入支付宝的快捷支付。
原创粉丝点击