package com.example.firstapp.activity
|
|
import android.os.Bundle
|
import android.webkit.WebView
|
import android.widget.Toast
|
import androidx.appcompat.app.AppCompatActivity
|
import androidx.lifecycle.lifecycleScope
|
import com.example.firstapp.R
|
import com.example.firstapp.database.service.RetrofitClient
|
import kotlinx.coroutines.launch
|
|
class ContentDetailActivity : AppCompatActivity() {
|
private lateinit var webView: WebView
|
private lateinit var toolbar: androidx.appcompat.widget.Toolbar
|
|
companion object {
|
const val ID = "id"
|
const val EXTRA_TITLE = "title"
|
}
|
|
override fun onCreate(savedInstanceState: Bundle?) {
|
super.onCreate(savedInstanceState)
|
setContentView(R.layout.activity_content_detail)
|
|
// 初始化视图
|
webView = findViewById(R.id.webView)
|
toolbar = findViewById(R.id.toolbar)
|
|
// 设置标题
|
val title = intent.getStringExtra(EXTRA_TITLE) ?: "内容详情"
|
toolbar.title = title
|
setSupportActionBar(toolbar)
|
supportActionBar?.setDisplayHomeAsUpEnabled(true)
|
toolbar.setNavigationOnClickListener { finish() }
|
|
// 获取内容类型
|
val id = intent.getStringExtra(ID)
|
if (id != null) {
|
loadContent(id)
|
} else {
|
Toast.makeText(this, "参数错误", Toast.LENGTH_SHORT).show()
|
finish()
|
}
|
}
|
|
private fun loadContent(id: String) {
|
lifecycleScope.launch {
|
try {
|
val response = RetrofitClient.apiService.getContentById(id)
|
if (response.code == "0" && response.data != null) {
|
// 构建HTML内容
|
val htmlContent = """
|
<!DOCTYPE html>
|
<html>
|
<head>
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<style>
|
body {
|
padding: 16px;
|
font-size: 16px;
|
line-height: 1.5;
|
}
|
</style>
|
</head>
|
<body>
|
${response.data.content}
|
</body>
|
</html>
|
|
|
|
|
""".trimIndent()
|
|
webView.loadDataWithBaseURL(null, htmlContent, "text/html", "UTF-8", null)
|
} else {
|
Toast.makeText(this@ContentDetailActivity, "获取内容失败", Toast.LENGTH_SHORT).show()
|
}
|
} catch (e: Exception) {
|
Toast.makeText(this@ContentDetailActivity, "网络错误", Toast.LENGTH_SHORT).show()
|
}
|
}
|
}
|
}
|