เมื่อสร้างโปรเจ็กส์ใหม่ขึ้นมาจะมี Activity หลักชื่อ MainActivity
เราจะสร้าง Activity เพิ่มขึ้นมาใหม่ชื่อ SecondActivity
การทำงานคือที่ MainActivity จะมีปุ่มไว้กดเรียก SecondActivity
และเมื่อถูกเรียกจะแสดงข้อความ “Second Activity”
ภาพที่ 3 มีการใส่ navigatoin ที่ AndroidManifest.xml
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="callSecondActivity" android:text="Call Second Activity" /> </LinearLayout> |
MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.phaisarn.myapplication import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } /** Called when the user taps the Send button */ fun callSecondActivity(view: View) { val intent = Intent(this, SecondActivity::class.java).apply {} startActivity(intent) } } |
activity_second.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".SecondActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Second Activity" android:textSize="18sp" /> </LinearLayout> |
AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.phaisarn.myapplication"> <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> <activity android:name=".SecondActivity" android:parentActivityName=".MainActivity"></activity> </application> </manifest> |
บรรทัดที่ 21 : ใส่ navigation หรือลูกศรย้อนกลับไปที่ MainActivity