【发布时间】:2021-03-20 05:51:31
【问题描述】:
所以我是 kotlin 的新手,我试图将设备上所有已安装的应用程序获取到回收站查看我的问题是回收站适配器中活动的所有内容都返回 null,即使我通过了上下文
这是我的代码:
class Games_listx : RecyclerView.Adapter<Games_listx.viewxlist>() {
var appsx = Gamesff()
var listofapps = ArrayList<String>()
var all_apps : MutableList<ApplicationInfo>? = null
var icons : Drawable? = null
class viewxlist(itemView: View) : RecyclerView.ViewHolder(itemView) {
val txt_game = itemView.findViewById<View>(R.id.txtgames) as TextView
val im_game = itemView.findViewById<View>(R.id.imgames) as ImageView
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Games_listx.viewxlist {
val layoutInflater = LayoutInflater.from(parent.context)
val view = layoutInflater.inflate(R.layout.lay_allgames,parent,false)
all_apps = appsx.activity?.packageManager?.getInstalledApplications(0)
Log.w("apps" , "app " + all_apps?.size)
for (app in all_apps?.indices!!) {
val name = all_apps?.get(app)?.loadLabel(appsx.activity?.packageManager!!)
if (!(name?.startsWith("com.")!!)) {
listofapps.add(name?.toString())
}
}
return viewxlist(view)
}
override fun getItemCount(): Int {
return listofapps.size
}
override fun onBindViewHolder(holder: Games_listx.viewxlist, position: Int) {
holder.txt_game.text = listofapps.get(position).toString()
}
}
listofapps 的大小为 0,包管理器为空
我使用相同的代码在 onstart 中获取应用程序并且它可以工作
我做错了什么
如何在适配器中不为空的情况下获取活动或上下文
片段中的回收站视图
class Gamesff : Fragment() {
override fun onStart() {
super.onStart()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val viewx = inflater.inflate(R.layout.fragment_gamesff,container,false)
val all_games_list = viewx.findViewById<View>(R.id.gamelistfounds) as RecyclerView
val add_game_folder = viewx.findViewById(R.id.txtaddgamefolder) as TextView
add_game_folder.setOnClickListener {
Toast.makeText(activity,"Make your own gaming folder",Toast.LENGTH_SHORT).show()
val i = Intent(activity,GamingFolder::class.java)
i.action = "add"
startActivity(i)
}
val gridlay = GridLayoutManager(activity,4,GridLayoutManager.VERTICAL,false)
all_games_list.layoutManager = gridlay
all_games_list.fitsSystemWindows = true
all_games_list.hasFixedSize()
all_games_list.adapter = Games_listx()
return viewx
}
【问题讨论】:
-
onCreateViewHolder被重复调用,为 RecyclerView 中的每个可见列表项视图组调用一次。如果您的列表为空,则一开始就不会调用它。您需要创建数据列表并将其填充到适配器类之外,然后将准备好的数据列表传递给适配器。 -
@Tenfour04 谢谢我知道适配器在java中是如何工作的你可以在适配器中处理你的数据并且可以访问上下文但是在kotlin它总是返回null它必须是方式
-
它在 Kotlin 和 Java 中的工作方式相同。您在
onCreateViewHolder()中获取已安装应用程序的列表,这没有任何意义。 -
@Tenfour04the 那么如何将活动中的应用程序信息中的可绘制对象传递给适配器而不是保存在数组中的路径呢?
标签: android android-layout kotlin android-recyclerview