我有一个包含MainActivity、ClientFragment和ConnectFragment的应用程序。我想将webView添加到ClientFragment。但是,当我尝试添加它时,我收到一个错误的未解析引用:查找查看者ID。
我已添加到MainActivity,但应用的其余部分无法正常工作。我应该如何以及在何处添加WebView?
package com.example.mqttkotlinsample
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.ImageButton
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import org.eclipse.paho.client.mqttv3.*
class ClientFragment : Fragment() {
private lateinit var mqttClient : MQTTClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (mqttClient.isConnected()) {
// Disconnect from MQTT Broker
mqttClient.disconnect(object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken?) {
Log.d(this.javaClass.name, "Disconnected")
Toast.makeText(context, "MQTT Disconnection success", Toast.LENGTH_SHORT).show()
// Disconnection success, come back to Connect Fragment
findNavController().navigate(R.id.action_ClientFragment_to_ConnectFragment)
}
override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
Log.d(this.javaClass.name, "Failed to disconnect")
}
})
} else {
Log.d(this.javaClass.name, "Impossible to disconnect, no server connected")
}
}
})
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_client, container, false)
//我已经尝试了这么多地方,但没有运气相同的错误未解析的引用:findViewById。
val webView = findViewById<View>(R.id.webView) as WebView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}}
我已将WebView放在xml文件中。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/mainwater"
tools:context=".ConnectFragment">
<WebView
android:id="@+id/webView"
android:layout_width="432dp"
android:layout_height="225dp"
android:layout_marginBottom="224dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView6" />
如果有人能帮我把这个工作,我会非常感激。
1条答案
按热度按时间hgb9j2n61#
我想明白了我只要把
val webView = view.findViewById<View>(R.id.webView) as WebView