有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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
        安卓:id="@+id/changeAppStateButton"
        安卓:layout_width="0dp"
        安卓:layout_height="45dp"
        安卓:layout_marginStart="16dp"
        安卓:layout_marginEnd="16dp"
        安卓:layout_marginBottom="110dp"
        安卓:background="#9C27B0"
        安卓:fontFamily="@font/alegreya_sans_sc"
        安卓:onClick="changeAppState"
        安卓:text="Start Reminder"
        安卓:textAlignment="center"
        安卓:textColor="#FFFFFF"
        安卓: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()在函数中不起作用吗?如果您需要更多的代码,请告诉我


共 (1) 个答案

  1. # 1 楼答案

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

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

    Button button = (Button) changeAppStateButton;
    

    (或者,正如@Ahtisham所指出的,如果您还没有获得对“更改应用程序状态”按钮的引用)

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

    因为这个新变量的类型是Button,所以您可以访问它的setText方法