Я пишу приложение, которое использует recyclerview для отображения списка запущенных приложений (значки и флажок для каждого). Итак, я могу нажать на приложение, чтобы установить флажок, и нажать кнопку выключения, чтобы закрыть выбранное приложение. Все работает, но когда дело доходит до проверки того, какое приложение выбрано для закрытия, список возвращает none или nil, хотя один из элементов списка должен быть выбран или отмечен.
Вот AppManager.kt
package com.example.activeapplist
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Process
import android.util.Log
import androidx.core.content.ContextCompat
class AppsManager(c: Context) {
private val mContext: Context = c
private val myApps: ArrayList
val apps: ArrayList
get() {
loadApps()
return myApps
}
private fun loadApps() {
val packages: List =
mContext.packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
for (packageInfo in packages) {
if(mContext.packageManager.getLaunchIntentForPackage(packageInfo.packageName) != null) {
//Get Apps that is running and are NOT System's APP
if (!isSYSTEM(packageInfo) && !isSTOPPED(packageInfo)) {
val newApp = AppInfo()
newApp.setAppName(getApplicationLabelByPackageName(packageInfo.packageName))
newApp.setAppPackage(packageInfo.packageName)
newApp.setAppIcon(getAppIconByPackageName(packageInfo.packageName))
newApp.setappID(packageInfo.uid)
myApps.add(newApp)
}
}
}
myApps.sortBy { it.getAppName() }
}
// Custom method to get application icon by package name
private fun getAppIconByPackageName(packageName: String): Drawable? {
val icon: Drawable?
icon = try {
mContext.packageManager.getApplicationIcon(packageName)
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
// Get a default icon
ContextCompat.getDrawable(mContext, R.drawable.ic_launcher_background)
}
return icon
}
// Custom method to get application label by package name
private fun getApplicationLabelByPackageName(packageName: String): String? {
val packageManager: PackageManager = mContext.packageManager
val applicationInfo: ApplicationInfo
var label = "Unknown"
try {
applicationInfo = packageManager.getApplicationInfo(packageName, 0)
if (applicationInfo != null) {
label = packageManager.getApplicationLabel(applicationInfo) as String
}
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return label
}
private fun isSTOPPED(pkgInfo: ApplicationInfo): Boolean {
return pkgInfo.flags and ApplicationInfo.FLAG_STOPPED != 0
}
private fun isSYSTEM(pkgInfo: ApplicationInfo): Boolean {
return pkgInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0
}
init {
myApps = ArrayList()
}
}
Вот Appinfo.kt
package com.example.activeapplist
import android.graphics.drawable.Drawable
class AppInfo {
private var appName: String? = null
private var appPackage: String? = null
private var appIcon: Drawable? = null
private var isSelected = false
private var mypid = 0
fun getAppPackage(): String? {
return appPackage
}
fun setAppPackage(appPackage: String?) {
this.appPackage = appPackage
}
fun getAppIcon(): Drawable? {
return appIcon
}
fun setAppIcon(appIcon: Drawable?) {
this.appIcon = appIcon
}
fun isSelected(): Boolean {
return isSelected
}
fun getappID() : Int {
return mypid
}
fun setappID(thepid: Int) {
mypid = thepid
}
fun setSelected(selected: Boolean) {
isSelected = selected
}
fun getAppName(): String? {
return appName
}
fun setAppName(appName: String?) {
this.appName = appName
}
}
Вот установленный адаптер
package com.example.activeapplist
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class InstalledAppsAdapter(context: Context, list: ArrayList) :
RecyclerView.Adapter() {
private val mContext: Context
private val mDataSet: ArrayList
class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
var mTextViewLabel: TextView
var mImageViewIcon: ImageView
var mAppSelect: CheckBox
var mItem: RelativeLayout
init {
// Get the widgets reference from custom layout
mTextViewLabel = v.findViewById(R.id.Apk_Name)
mImageViewIcon = v.findViewById(R.id.packageImage) as ImageView
mAppSelect = v.findViewById(R.id.appSelect)
mItem = v.findViewById(R.id.item)
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ViewHolder {
val v: View =
LayoutInflater.from(mContext).inflate(R.layout.each_appy, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {
// Get the current package name
val packageName: String? = mDataSet[position].getAppPackage()
// Get the current app icon
val icon: Drawable? = mDataSet[position].getAppIcon()
// Get the current app label
val label: String? = mDataSet[position].getAppName()
// Set the current app label
holder.mTextViewLabel.text = label
// Set the current app icon
holder.mImageViewIcon.setImageDrawable(icon)
holder.mAppSelect.isChecked = mDataSet[position].isSelected()
holder.mItem.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
mDataSet[position].setSelected(!mDataSet[position].isSelected())
notifyDataSetChanged()
}
})
}
override fun getItemCount(): Int {
// Count the installed apps
return mDataSet.size
}
init {
mContext = context
mDataSet = list
}
}
Вот MainActivity.kt
package com.example.activeapplist
import android.app.Activity
import android.app.ActivityManager
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.ActiveAppList.MyAccessibilityService
import java.util.ArrayList
import java.util.Timer
import kotlin.concurrent.schedule
class MainActivity : AppCompatActivity() {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter? = null
private var installedApps: ArrayList? = null
private var getListButton: Button? = null
private var selectAllButton: Button? = null
private var unselectAllButton: Button? = null
private var shutdownNowButton: Button? = null
private var appManager: AppsManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.hide()
checkAndEnableAccessibilityService()
installedApps = ArrayList()
mRecyclerView = findViewById(R.id.recyclerView)!!
getListButton = findViewById(R.id.getAppBtn)!!
selectAllButton = findViewById(R.id.SelectAllBtn)!!
unselectAllButton = findViewById(R.id.UnSelectAllBtn)!!
shutdownNowButton = findViewById(R.id.ShutdownNowBtn)!!
val layoutManager = LinearLayoutManager(this)
mRecyclerView!!.layoutManager = layoutManager
appManager = AppsManager(this)
installedApps = appManager!!.apps
getListButton?.setOnClickListener()
{
installedApps!!.clear()
mRecyclerView?.adapter?.notifyDataSetChanged()
Timer().schedule(2000) { }
installedApps = appManager!!.apps
mRecyclerView?.adapter?.notifyDataSetChanged()
// displaying a toast message
Toast.makeText(this@MainActivity, "List Updated", Toast.LENGTH_LONG).show()
}
selectAllButton?.setOnClickListener()
{
for (pos in installedApps!!.indices) {
installedApps!![pos].setSelected(true)
}
mRecyclerView?.adapter?.notifyDataSetChanged()
Toast.makeText(this@MainActivity, "All Apps Selected", Toast.LENGTH_LONG).show()
}
unselectAllButton?.setOnClickListener()
{
for (pos in installedApps!!.indices) {
installedApps!![pos].setSelected(false)
}
mRecyclerView?.adapter?.notifyDataSetChanged()
Toast.makeText(this@MainActivity, "All Apps Unselected", Toast.LENGTH_LONG).show()
}
shutdownNowButton?.setOnClickListener()
{
installedApps!!.clear()
installedApps = appManager!!.apps
for (pos in installedApps!!.indices) {
if (installedApps!![pos].isSelected()){
Toast.makeText(
this@MainActivity,
installedApps!![pos].getAppPackage(),
Toast.LENGTH_LONG
).show()
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", installedApps!![pos].getAppPackage(), null)
intent.data = uri
startActivity(intent)
}
}
installedApps!!.clear()
installedApps = appManager!!.apps
mRecyclerView?.adapter?.notifyDataSetChanged()
}
// Initialize a new adapter for RecyclerView
mAdapter = InstalledAppsAdapter(
applicationContext,
installedApps!!
)
mRecyclerView!!.adapter = mAdapter
}
private fun checkAndEnableAccessibilityService() {
if (!isAccessibilityServiceEnabled()) {
val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
startActivity(intent)
}
if (!Settings.canDrawOverlays(this)) {
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:ActiveAppList")
)
startActivityForResult(intent, 0)
}
}
private fun isAccessibilityServiceEnabled(): Boolean {
return Settings.Secure.getString(contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
?.contains("${packageName}/${MyAccessibilityService::class.java.canonicalName}") == true
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... -being-app
Android Kotlin – почему изменение состояния флажка в списке recyclerview не применяется? ⇐ Android
Форум для тех, кто программирует под Android
1764608708
Anonymous
Я пишу приложение, которое использует recyclerview для отображения списка запущенных приложений (значки и флажок для каждого). Итак, я могу нажать на приложение, чтобы установить флажок, и нажать кнопку выключения, чтобы закрыть выбранное приложение. Все работает, но когда дело доходит до проверки того, какое приложение выбрано для закрытия, список возвращает none или nil, хотя один из элементов списка должен быть выбран или отмечен.
Вот AppManager.kt
package com.example.activeapplist
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Process
import android.util.Log
import androidx.core.content.ContextCompat
class AppsManager(c: Context) {
private val mContext: Context = c
private val myApps: ArrayList
val apps: ArrayList
get() {
loadApps()
return myApps
}
private fun loadApps() {
val packages: List =
mContext.packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
for (packageInfo in packages) {
if(mContext.packageManager.getLaunchIntentForPackage(packageInfo.packageName) != null) {
//Get Apps that is running and are NOT System's APP
if (!isSYSTEM(packageInfo) && !isSTOPPED(packageInfo)) {
val newApp = AppInfo()
newApp.setAppName(getApplicationLabelByPackageName(packageInfo.packageName))
newApp.setAppPackage(packageInfo.packageName)
newApp.setAppIcon(getAppIconByPackageName(packageInfo.packageName))
newApp.setappID(packageInfo.uid)
myApps.add(newApp)
}
}
}
myApps.sortBy { it.getAppName() }
}
// Custom method to get application icon by package name
private fun getAppIconByPackageName(packageName: String): Drawable? {
val icon: Drawable?
icon = try {
mContext.packageManager.getApplicationIcon(packageName)
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
// Get a default icon
ContextCompat.getDrawable(mContext, R.drawable.ic_launcher_background)
}
return icon
}
// Custom method to get application label by package name
private fun getApplicationLabelByPackageName(packageName: String): String? {
val packageManager: PackageManager = mContext.packageManager
val applicationInfo: ApplicationInfo
var label = "Unknown"
try {
applicationInfo = packageManager.getApplicationInfo(packageName, 0)
if (applicationInfo != null) {
label = packageManager.getApplicationLabel(applicationInfo) as String
}
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return label
}
private fun isSTOPPED(pkgInfo: ApplicationInfo): Boolean {
return pkgInfo.flags and ApplicationInfo.FLAG_STOPPED != 0
}
private fun isSYSTEM(pkgInfo: ApplicationInfo): Boolean {
return pkgInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0
}
init {
myApps = ArrayList()
}
}
Вот Appinfo.kt
package com.example.activeapplist
import android.graphics.drawable.Drawable
class AppInfo {
private var appName: String? = null
private var appPackage: String? = null
private var appIcon: Drawable? = null
private var isSelected = false
private var mypid = 0
fun getAppPackage(): String? {
return appPackage
}
fun setAppPackage(appPackage: String?) {
this.appPackage = appPackage
}
fun getAppIcon(): Drawable? {
return appIcon
}
fun setAppIcon(appIcon: Drawable?) {
this.appIcon = appIcon
}
fun isSelected(): Boolean {
return isSelected
}
fun getappID() : Int {
return mypid
}
fun setappID(thepid: Int) {
mypid = thepid
}
fun setSelected(selected: Boolean) {
isSelected = selected
}
fun getAppName(): String? {
return appName
}
fun setAppName(appName: String?) {
this.appName = appName
}
}
Вот установленный адаптер
package com.example.activeapplist
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class InstalledAppsAdapter(context: Context, list: ArrayList) :
RecyclerView.Adapter() {
private val mContext: Context
private val mDataSet: ArrayList
class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
var mTextViewLabel: TextView
var mImageViewIcon: ImageView
var mAppSelect: CheckBox
var mItem: RelativeLayout
init {
// Get the widgets reference from custom layout
mTextViewLabel = v.findViewById(R.id.Apk_Name)
mImageViewIcon = v.findViewById(R.id.packageImage) as ImageView
mAppSelect = v.findViewById(R.id.appSelect)
mItem = v.findViewById(R.id.item)
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ViewHolder {
val v: View =
LayoutInflater.from(mContext).inflate(R.layout.each_appy, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {
// Get the current package name
val packageName: String? = mDataSet[position].getAppPackage()
// Get the current app icon
val icon: Drawable? = mDataSet[position].getAppIcon()
// Get the current app label
val label: String? = mDataSet[position].getAppName()
// Set the current app label
holder.mTextViewLabel.text = label
// Set the current app icon
holder.mImageViewIcon.setImageDrawable(icon)
holder.mAppSelect.isChecked = mDataSet[position].isSelected()
holder.mItem.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
mDataSet[position].setSelected(!mDataSet[position].isSelected())
notifyDataSetChanged()
}
})
}
override fun getItemCount(): Int {
// Count the installed apps
return mDataSet.size
}
init {
mContext = context
mDataSet = list
}
}
Вот MainActivity.kt
package com.example.activeapplist
import android.app.Activity
import android.app.ActivityManager
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.ActiveAppList.MyAccessibilityService
import java.util.ArrayList
import java.util.Timer
import kotlin.concurrent.schedule
class MainActivity : AppCompatActivity() {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter? = null
private var installedApps: ArrayList? = null
private var getListButton: Button? = null
private var selectAllButton: Button? = null
private var unselectAllButton: Button? = null
private var shutdownNowButton: Button? = null
private var appManager: AppsManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.hide()
checkAndEnableAccessibilityService()
installedApps = ArrayList()
mRecyclerView = findViewById(R.id.recyclerView)!!
getListButton = findViewById(R.id.getAppBtn)!!
selectAllButton = findViewById(R.id.SelectAllBtn)!!
unselectAllButton = findViewById(R.id.UnSelectAllBtn)!!
shutdownNowButton = findViewById(R.id.ShutdownNowBtn)!!
val layoutManager = LinearLayoutManager(this)
mRecyclerView!!.layoutManager = layoutManager
appManager = AppsManager(this)
installedApps = appManager!!.apps
getListButton?.setOnClickListener()
{
installedApps!!.clear()
mRecyclerView?.adapter?.notifyDataSetChanged()
Timer().schedule(2000) { }
installedApps = appManager!!.apps
mRecyclerView?.adapter?.notifyDataSetChanged()
// displaying a toast message
Toast.makeText(this@MainActivity, "List Updated", Toast.LENGTH_LONG).show()
}
selectAllButton?.setOnClickListener()
{
for (pos in installedApps!!.indices) {
installedApps!![pos].setSelected(true)
}
mRecyclerView?.adapter?.notifyDataSetChanged()
Toast.makeText(this@MainActivity, "All Apps Selected", Toast.LENGTH_LONG).show()
}
unselectAllButton?.setOnClickListener()
{
for (pos in installedApps!!.indices) {
installedApps!![pos].setSelected(false)
}
mRecyclerView?.adapter?.notifyDataSetChanged()
Toast.makeText(this@MainActivity, "All Apps Unselected", Toast.LENGTH_LONG).show()
}
shutdownNowButton?.setOnClickListener()
{
installedApps!!.clear()
installedApps = appManager!!.apps
for (pos in installedApps!!.indices) {
if (installedApps!![pos].isSelected()){
Toast.makeText(
this@MainActivity,
installedApps!![pos].getAppPackage(),
Toast.LENGTH_LONG
).show()
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", installedApps!![pos].getAppPackage(), null)
intent.data = uri
startActivity(intent)
}
}
installedApps!!.clear()
installedApps = appManager!!.apps
mRecyclerView?.adapter?.notifyDataSetChanged()
}
// Initialize a new adapter for RecyclerView
mAdapter = InstalledAppsAdapter(
applicationContext,
installedApps!!
)
mRecyclerView!!.adapter = mAdapter
}
private fun checkAndEnableAccessibilityService() {
if (!isAccessibilityServiceEnabled()) {
val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
startActivity(intent)
}
if (!Settings.canDrawOverlays(this)) {
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:ActiveAppList")
)
startActivityForResult(intent, 0)
}
}
private fun isAccessibilityServiceEnabled(): Boolean {
return Settings.Secure.getString(contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
?.contains("${packageName}/${MyAccessibilityService::class.java.canonicalName}") == true
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79835076/android-kotlin-why-checkbox-state-change-in-recyclerview-list-is-not-being-app[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия