Android環境搭建及demo

Android環境搭建及demo

環境搭建

  1. 安裝android sdk
    File --> Settings --> Appearance & Behavior --> System Settings --> Android SDK
    在這裏插入圖片描述2. 配置ANDROID_HOME
export ANDROID_HOME=/opt/Android

項目

程序入口:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

onCreate爲初始化。
setContentView設置屏幕展示的View, View通過layout_.xml在res中定義, 並且在編譯時自動生成R.java程序。
findViewById獲取layout_
.xml中定義的Viewid

資源定義方式:

    <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=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

@mipmap/ic_launcher引用mipmap文件夾下的ic_launcher.xml文件中的內容。
@string/app_name引用values/strings.xml中的<string>部分<string name="app_name">My Application</string>
@mipmap/ic_launcher_round引用mipmap文件夾下的ic_launcher_round文件中的內容。
@style/AppTheme引用values/styles.xml中的主題。

layout定義:

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="79dp"
        android:layout_marginLeft="79dp"
        android:layout_marginBottom="61dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

@+id/button定義的id會編譯進R.java中,代碼中引用如下:

    mTimes = 0L;
    mView = findViewById(R.id.text);
    mButton = findViewById(R.id.button);
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mTimes++;
            Toast toast = Toast.makeText(MainActivity.this, "clicked!", Toast.LENGTH_LONG);
            toast.show();
            mView.setText("" + mTimes);
        }
    });

Toast.makeText用戶彈出消息。

發佈了123 篇原創文章 · 獲贊 7 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章