第二章 Activity(一)——簡單的Activity創建

1.什麼是Acivity

用戶交互界面:在無邊界的天空打開了一個天窗。

2.運行一個簡單的Activity

2.1 JAVA:

package com.field.activitydemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

/**
 * MainActivity 需要 繼承 AppCompatActivity
 * 
 */
public class MainActivity extends AppCompatActivity {
    
    //2.對象的使用範圍 是否定義全局變量
    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //3.給當前活動綁定佈局
        setContentView(R.layout.activity_main);
        //4.初始化view 用於加載控件 注意控件只有在先加載 然後再調用,否則會報空指針
        initView();
    }

    private void initView() {
        //加載控件
        mTextView = findViewById(R.id.tv);
    }
}

2.2 XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
<!--xml 創建文本控件 注意需要在代碼中需要給控件對象 使用 setter getter方法的時候 加上id
        設置text的時候 最好用存入res,values ,strings 內部
        方便本地化-->
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/hello_man"/>

</RelativeLayout>

2.3 AndroidManifest.xml:

如果自定義的Activity沒有在這裏註冊,會報異常:

Unable to find explicit activity class ..; have you declared this activity in your AndroidManifest.xml?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.field.activitydemo">

    <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=".LifeActivity"></activity>
       
       <!--配置文件 將MainActivity 註冊在AndroidManifest.xml -->
        <activity android:name=".MainActivity">
            <!--過濾器 app啓動後 打開的主界面 action 表示是主界面 category 表示啓動
            備註:可以給app 設置多個 啓動界面 會有意想不到的效果-->
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

3.小記:

	java 代碼控制與用戶交互的數據。xml 顯示view(修改xml編譯的時間 大於 修改代碼編譯的時間)。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章