Java 单击按钮后如何更改按钮文本?

Java 单击按钮后如何更改按钮文本?,java,android,onclick,counter,Java,Android,Onclick,Counter,我是Android新手,在我的课堂上,我们必须制作一个程序,每次按下一个按钮,计数就会增加,这个数字会显示在按钮内。例如,按钮从0开始,我单击按钮,它将文本从0更改为1,然后再次单击,它将从1更改为2,依此类推,但按钮中的数字会更改。不使用TextView是否可以执行类似操作 这是我在activity_main.xml上的内容 <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.Con

我是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>

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

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

您需要在侦听单击事件的按钮上设置onClick侦听器

findViewById(R.id.button).setOnClickListener(clickListener);
...

private View.OnClickListener clickListener = v -> {
    int count = Integer.parseInt(((Button) v).getText().toString());
    ((Button) v).setText(String.valueOf(++count));
};

应用程序正在崩溃?按钮继承自TextView,因此您只需在其上使用setText()。虽然此代码可能会解决此问题,但如何以及为什么解决此问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释,并说明适用的限制和假设。虽然这可能是一个有效的答案,但最好提供一些解释。感谢您的反馈,我已用解释更新了我的答案。
findViewById(R.id.button).setOnClickListener(clickListener);
...

private View.OnClickListener clickListener = v -> {
    int count = Integer.parseInt(((Button) v).getText().toString());
    ((Button) v).setText(String.valueOf(++count));
};
public class MainActivity extends AppCompatActivity {

    Button button;

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

        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String str = (String) button.getText();
                int i = Integer.parseInt(str);
                button.setText(String.valueOf(++i));

            }
        });
    }
}