如何在 Android ListView 中使用 Kotlin 檢測向上和向下滾動?
此示例演示瞭如何在 Android ListView 中使用 Kotlin 檢測向上和向下滾動。
步驟 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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="8dp" tools:context=".MainActivity"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
步驟 3 - 將以下程式碼新增到 src/MainActivity.kt 中。
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var scrollView: ScrollView? = null
private lateinit var listView: ListView
private var numbers = arrayOf(
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"X",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25"
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
scrollView = findViewById(R.id.scrollView)
val adapter: ArrayAdapter<*> = ArrayAdapter(
this,
R.layout.support_simple_spinner_dropdown_item, numbers
)
listView = findViewById(R.id.listView)
listView.adapter = adapter
listView.setOnScrollListener(object : AbsListView.OnScrollListener {
private var lastFirstVisibleItem = 0
override fun onScrollStateChanged(view: AbsListView, scrollState: Int) {}
override fun onScroll(
view: AbsListView,
firstVisibleItem: Int,
visibleItemCount: Int,
totalItemCount: Int
)
{
if (lastFirstVisibleItem < firstVisibleItem) {
Toast.makeText(
applicationContext, "Scrolling down the listView",
Toast.LENGTH_SHORT
).show()
}
if (lastFirstVisibleItem > firstVisibleItem) {
Toast.makeText(
applicationContext, "Scrolling up the listView",
Toast.LENGTH_SHORT
).show()
}
lastFirstVisibleItem = firstVisibleItem
}
})
}
}步驟 4 - 將以下程式碼新增到 androidManifest.xml 中。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <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 執行該應用程式,請開啟您專案中的一個活動檔案,然後單擊工具欄中的執行
圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕。


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