## **手動創建一個Android項目**
1. 新建一個Android項目,項目名稱可以叫作ActivityTest;
2. 選擇Add No Activity;

3. 點擊Finish
## **手動創建活動**
1. 在com.lowthink.activitytest上點右鍵然后如圖所示選擇

2. 將活動命名為FirstActivity,并且不要勾選Generate Layout File和Launcher Activity這兩個選項
Generate Layout :勾選表示會自動為FirstActivity創建一個對應的布局文件
Launcher Activity:勾選表示會自動將FirstActivity設置為當前項目的主活動;
Backwards Compatibility 表示會為項目啟用向下兼容的模式,這個選項要勾上。

3. 點擊Finish;
注:你需要知道,項目中的任何活動都應該重寫Activity的onCreate()方法
打開新建的FirstActivity可以看到如下代碼已經被AndroidStudio創建好了:
~~~
package com.lowthink.activitytest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
~~~
## **創建和加載布局**
1. 右鍵app/src/main/res目錄->New->Directory,會彈出一個新建目錄的窗口,這里先創建一個名為layout的目錄;
2. 然后對這layout目錄右鍵->New->Layout resource file,添加布局文件名稱first_layout,根元素就默認選擇為LinearLayout。
3. 點擊OK
4. 點擊Text選項卡可以看到如下代碼:
~~~
<?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">
</LinearLayout>
~~~
5. 添加一個按鈕,如下所示
~~~
<?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/id_name表示引用一個id,@+id/id_name表示定義一個id)
* android:layout_width 指定了當前元素的寬度,這里是喲好難過match_parent表示讓當前元素和父元素一樣寬。
* android:layout_height 指定了當前元素的高度,這里使用wrap_content表示當前元素的高度只要能剛好包含里面的內容就行。
* android:text 指定了元素中顯示的文字內容。
6. 重新回到FirstActivity,在onCreate()方法中加入如下代碼:
~~~
package com.lowthink.activitytest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
}
}
~~~
setContentView()方法來給當前的活動加載一個布局,而在setContentView()方法中,我們一般都會傳入一個布局文件的id,項目中添加的任何資源都會在R文件中生成一個相應的資源id,因此我們剛才創建的first_layout.xml 布局的id現在應該是已經添加到R文件中了。
## **在AndroidMainfest文件中注冊**
- Android第一行代碼(第二版)筆記
- 第1章
- 1.1.3 Android應用開發特色
- 1.2搭建開發環境
- 1.3創建你的第一個Android項目
- 1.3.4分析你的第一個Android程序
- 1.3.5 詳解項目中的資源
- 1.3.6 詳解build.gradle文件
- 1.4掌握日志工具的使用
- 第2章
- 2.1活動是什么
- 2.2活動的基本用法
- Android開發規范
- Android Studio配置打包生成自定義文件名
- 開發問題記錄
- Android resource compilation failed( com.android.support沖突)
- 關于Android原生集成5+webview,監聽webview返回時,執行兩次onkey方法問題的解決
- java先關基礎鞏固
- URI與URL詳解