java - 如何更改 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));
}
}
解决方案
EditText 仅接受字符串值,因为计数器变量是整数,因此应用程序崩溃,最好将其转换为字符串,然后将其设置为 edittext
showValue.setText(String.valueOf(counter));
推荐阅读
- python - 将列重新排列到熊猫中的下一行
- java - 如何在给定字符串中获取 \" 字符串的正则表达式
- sql - 尝试在 SQL 中插入多行时出现语法错误?
- c# - 如何仅在当前页面顶部/覆盖当前页面上显示 ProgressRing 控件?
- vue.js - VueJs CLI 3 - 如何添加外部库
- java - Hibernate 在整个 Spring Boot 应用程序上设置属性访问策略
- java - Java Base64.getDecoder().decode() c# 等效
- solr - Solr 数据导入 12/12 已获取但 0/12 已处理
- python-3.x - py2app 捆绑系统 MacOSX python 2.7 而不是 python 3
- java - 如何让用户保持登录到 WebView 应用程序?