如何使用 Kotlin 在 Android 中获取一个工作的垂直 SeekBar?
本例演示如何使用 kotlin 在 Android 后台服务中监听音量按钮。
步骤 1 − 在 Android Studio 中创建一个新项目,转到文件?新建项目,并填写所有必需的详细信息来创建一个新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。
示例
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:padding="8dp" tools:context=".MainActivity"> <SeekBar android:id="@+id/seekBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:rotation="270" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:text="" android:textSize="16sp" /> </RelativeLayout>
步骤 3 − 将以下代码添加到 src/MainActivity.kt
示例
import android.os.Bundle
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var seekBar: SeekBar
lateinit var textView: TextView
var min = 0
var max: Int = 100
var current: Int = 50
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
seekBar = findViewById(R.id.seekBar)
seekBar.progress = max - min
seekBar.progress = current - min
textView.text = "" + current
seekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
current = progress + min
textView.text = "" + current
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
}
}步骤 4 − 将以下代码添加到 src/SettingsContentObserver.kt
示例
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.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> </application> </manifest>
让我们尝试运行你的应用程序吧。我假设你已经将你的真机 Android 移动设备与电脑连接。要在 android studio 中运行应用程序,打开你的一个项目活动文件并从工具栏中单击运行图标
。选择你的移动设备作为选项,然后检查你的移动设备,它会显示你的默认屏幕

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP