首页 > 解决方案 > 如何更改 onClick 上的按钮文本?

问题描述

我是 Android 新手,在我的课堂上,我们必须编写一个程序,每次按下按钮时计数都会增加,并且这个数字会显示在按钮内。例如,按钮从 0 开始,我单击按钮并将文本从 0 更改为 1,然后再次单击它从 1 变为 2,依此类推,但按钮中的数字会发生变化。是否可以在不使用 TextView 的情况下做这样的事情?

这就是我的 activity_main.xml

<?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">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="countUp"
        android:text="0"
        tools:layout_editor_absoluteX="72dp"
        tools:layout_editor_absoluteY="61dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

这就是我的 MainActivity.java

package com.example.tapgrid;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button showValue;
    int counter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showValue = (Button) findViewById(R.id.button);
    }

    public void countUp (Button view) {
        counter++;
        showValue.setText(Integer.toString(counter));
    }

}

标签: javaandroidonclickcounter

解决方案


EditText 仅接受字符串值,因为计数器变量是整数,因此应用程序崩溃,最好将其转换为字符串,然后将其设置为 edittext

showValue.setText(String.valueOf(counter));

推荐阅读