如何使用 Kotlin 從 Android 應用程式中開啟 Facebook 頁面?
此示例演示瞭如何使用 Kotlin 從 Android 應用程式中開啟 Facebook 頁面
步驟 1 − 在 Android Studio 中建立一個新專案,選擇檔案 ⇒ 新專案,並填寫所有必需的詳細資訊來建立一個新專案。
步驟 2 − 向 res/layout/activity_main.xml 中新增以下程式碼。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rlMain" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="30dp" android:layout_marginBottom="30dp" android:onClick="fbClick" android:text="open Facebook" /> </LinearLayout>
步驟 3 − 向 src/MainActivity.kt 中新增以下程式碼
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun fbClick(view: View) {
startActivity(getOpenFacebookIntent());
}
private fun getOpenFacebookIntent(): Intent? {
return try {
packageManager.getPackageInfo("com.facebook.katana", 0)
Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/426253597411506"))
} catch (e: Exception) {
Intent(Intent.ACTION_VIEW, Uri.parse("https://#/appetizerandroid"))
}
}
}步驟 4 − 向 androidManifest.xml 中新增以下程式碼
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11"> <uses-permission android:name="android.permission.INTERNET"/> <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> </manifest>
讓我們嘗試執行我們的應用程式。假設您已將您的實際 Android 移動裝置連線至您的計算機。要從 Android Studio 執行應用程式,請開啟您的某項專案活動檔案,並單擊工具欄的執行圖示
。選擇您的移動裝置作為選項,然後檢查顯示預設介面的移動裝置


廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP