这是我的第一个android应用程序,我试图用一些文本填充textView对象。
当我尝试将文本设置为已声明的TextView对象时:
val textView = findViewById<TextView>(R.id.textView)
textView.text = 'hello'
产生错误,指出“预期成员声明”
似乎Android Studio无法识别该声明。
链接到我在rStudio中的代码的图片(尚不能直接发布图片):
https://drive.google.com/file/d/1jXaU4Fd6_hIhqRuLLbS-SG7uFscK8eOW/view?usp=sharing
https://drive.google.com/file/d/1-AQW_943cL7TzqS8gczQCY25z8-3mDVo/view?usp=sharing
我努力了:
1)清理并重建项目。
2)将textView设置为“hello”(双引号)和一个字符串变量。
我可以在我的应用程序中的其他 Activity 中使用相同的过程将文本设置为textview对象,但是我不能在这里这样做。我敢肯定,这是我的愚蠢之举,但我只是看不到它。
请让我知道是否需要澄清或需要提供更多信息。
package com.example.appzilla
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.TextView
import androidx.cardview.widget.CardView
class Place_Page : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.place_page)
}
val textView = findViewById<TextView>(R.id.textView)
textView.text = 'hello'
val place : Place = intent.getParcelableExtra("Extra_Place")
}
<?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=".Place_Page">
<TextView
android:id="@+id/textView"
android:layout_width="300dp"
android:layout_height="150dp"
android:layout_marginStart="8dp"
android:layout_marginTop="268dp"
android:layout_marginEnd="8dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.494"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
最佳答案
将您的textview行放在oncreate方法中。 Findviewbyid仅在setcontentview之后起作用。
关于kotlin - Android Studio要求在成员已声明后声明成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55563349/