我使用了TextView,并使其在Kotlin中可单击。这是一个语音识别应用程序,当我单击文本视图时,我希望它进入另一个活动。
class STTFragment : Fragment() {
lateinit var recognizer: SpeechRecognizer
lateinit var chatPresenter: IChatPresenter
private val thisActivity = activity
override fun onAttach(context: Context?) {
super.onAttach(context)
chatPresenter = ChatPresenter(requireContext())
}
@NonNull
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_sttframe, container, false)
if (thisActivity is ChatActivity)
thisActivity.fabsetting.hide()
promptSpeechInput()
setupCommands(rootView)
return rootView
}
private fun setupCommands(rootView: View) {
var voiceCommand = getResources().getStringArray(R.array.voiceCommands)
var voiceCommandsList = voiceCommand.toCollection(ArrayList())
rootView.clickableCommands.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
rootView.clickableCommands.adapter = VoiceCommandsAdapter(voiceCommandsList, activity)
}
那是 sttFragment 类
class VoiceCommandsAdapter(val items: ArrayList<String>, val context: Context?) : RecyclerView.Adapter<VoiceCommandsAdapter.ViewHolder>() {
lateinit var chatPresenter: IChatPresenter
override fun onCreateViewHolder(parent: ViewGroup, p1: Int): ViewHolder {
chatPresenter = ChatPresenter(context as Context)
return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_voice_commands, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder?.voiceCommand?.text = items.get(position)
}
override fun getItemCount(): Int {
return items.size
}
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val voiceCommand: TextView = view.voiceCommand
init {
view.setOnClickListener {
val chatMessage = items[adapterPosition]
val splits = chatMessage.split("\n".toRegex()).dropLastWhile { it.isEmpty() }
val message = splits.joinToString(" ")
if (!chatMessage.isEmpty()) {
chatPresenter.sendMessage(message, items[adapterPosition])
}
}
}
}
}
这是 voicecommandAdapter 类。 我该如何修改代码,以便在单击该命令后立即转到另一个活动。
它不应该等到识别器超时。
答案 0 :(得分:0)
我会尽量简洁明了。正确的方法是:
VoiceCommandsAdapter(val items: ArrayList<String>, val context: Context?, val clickListener: View.OnClickListener)
onClick()
功能 在您的onBindViewHolder
中,将点击侦听器添加到TextView
holder?.voiceCommand?.text.setOnClickListener {clickListener.onClick()}
在下一步(也是最后一步)之前注意:您所做的只是将click回调传递给适配器,这样,当您单击TextView时,它将返回到片段onClick(View)
函数。
这是一个好习惯,因为您想在片段中进行下一步,这就是导航部分。
这里的替代方法是将活动实例传递给适配器,并在那里处理导航逻辑,但这是不好的做法(将活动/片段实例传递给周围)
onClick(View)
中STTFragment
中的新活动 onClick(View)
函数内部,您将在其中触发导航逻辑。为此,只需添加:val intent = Intent(activity, TargetActivity.class)
activity.startActivity(intent)