gpt4 book ai didi

java - 当我尝试在按钮上使用 setText() 时,为什么 Android Studio 显示错误?

转载 作者:行者123 更新时间:2023-12-01 17:29:42 25 4
gpt4 key购买 nike

我正在制作一个应用程序,只要手机处于 sleep /空闲状态,我就尝试运行计时器。手机一开机,计时器就会停止。
这是 main.java 中的(相关)代码:

public void changeAppState(View view) {
view = (Button) changeAppStateButton;
Log.i("BUTTON", "Tapped!");
if (isAppRunning) { //If the app is running, stop app
isAppRunning = false;
view.setBackgroundColor(getColor(R.color.colorPurple));
view.setText("Start Reminder"); //There's an error here
timer.cancel();
Log.i("TIMER", "Timer interrupted");

} else { //If the app is not running, start app
//some code

isAppRunning = true;
view.setBackgroundColor(getColor(R.color.colorRed));
view.setText("Stop Reminder"); //There's an error here

//some more code
}
}

这是按钮的 XML:

    <Button
android:id="@+id/changeAppStateButton"
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="110dp"
android:background="#9C27B0"
android:fontFamily="@font/alegreya_sans_sc"
android:onClick="changeAppState"
android:text="Start Reminder"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />

Android Studio 会突出显示函数中两次出现的 setText()。我没有看到任何错误消息。有人能告诉我为什么 setText() 在该函数中不起作用吗?如果您需要更多代码,请告诉我。

最佳答案

重新分配 view 不会将变量的类型从 View 更改为 Button,因为它会自动重新转换回查看

相反,您需要初始化 Button 类型的变量,如下所示:

Button button = (Button) changeAppStateButton;

(或者,如 @Ahtisham 所指出的,如果您尚未获得更改应用程序状态按钮的引用)

Button button = findViewById(R.id.changeAppStateButton);

由于这个新变量的类型为 Button,因此您将能够访问其 setText 方法。

关于java - 当我尝试在按钮上使用 setText() 时,为什么 Android Studio 显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61145521/

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