gpt4 book ai didi

android - 连接 Kotlin-Variable 和 Activity-XML

转载 作者:行者123 更新时间:2023-11-30 04:54:03 25 4
gpt4 key购买 nike

我开始为 Android 开发一个应用程序。之前,我有多年使用 C++/Python 和 QT/PySide(所有内容都是手写的)的经验,因此,处理 xml 中的 GUI 和 kt 文件中的操作让我感到非常困惑。现在我在 Android Studio 中使用 Kotlin。在我按照过时的教程进行操作后,我尝试使用文本编辑器(用于 url)、“开始”按钮和用于显示站点的 webview 来获得一个非常简单的“浏览器”。

在让 Webview(在教程的帮助下)以我想要的方式工作之后,我现在偶然发现了这个:

<?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"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:elevation="4dp">

<EditText
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
android:text="" />

<Button
android:id="@+id/button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Go" />
</LinearLayout>

<WebView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.8"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

TextView text = (TextView) findViewById(R.id.text)
Button button = (Button) findViewById(R.id.button)
}
}

在 TextView 和 Button 上我得到了错误:“预期函数调用‘TextView(...)’”(或者,而不是 TextView:Button)。我必须做什么才能让 View 连接到我的函数?

感谢您的帮助!

最佳答案

下面这部分代码不是Kotlin,而是Java。

    TextView text = (TextView) findViewById(R.id.text)
Button button = (Button) findViewById(R.id.button)

这是用 Kotlin 编写的等效代码

    val text = findViewById<TextView>(R.id.text)
val button = findViewById<Button>(R.id.button)

点击here阅读更多关于 Kotlin 基本语法的信息。和 here你可以在 Java 和 Kotlin 之间找到很好的比较。

关于android - 连接 Kotlin-Variable 和 Activity-XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com