Android开发:如何让按钮点击后计数器与指定字符串一同显示?
Hey, let's get this sorted out quickly! The root cause here is pretty clear: when you update your TextView after clicking the button, you're only setting the counter's numeric value instead of combining it with the "Hello World" prefix you want.
问题分析
Your initial goal is to start with "Hello World!" and then show "Hello World 1", "Hello World 2", etc., each time the button is clicked. Right now, you're probably doing something like showValue.setText(String.valueOf(counter)); which only outputs the number—we just need to add the text prefix to that.
修正后的完整代码
Here's the fixed version of your MainActivity with all necessary parts filled in:
package com.example.victornguyen.updatedengrassignment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView showValue; int counter = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 绑定布局中的TextView控件 showValue = findViewById(R.id.text_view_counter); // 设置初始显示文本"Hello World!" showValue.setText("Hello World!"); } // 按钮点击触发的方法(需和布局中Button的android:onClick属性值一致) public void updateCounter(View view) { counter++; // 拼接前缀文本与计数器数值 showValue.setText("Hello World " + counter); // 也可以用更规范的格式化写法: // showValue.setText(String.format("Hello World %d", counter)); } }
关键修正点
- 初始文本设置:在
onCreate方法中给TextView设置初始值"Hello World!",符合你预期的初始显示效果。 - 文本拼接逻辑:在按钮点击方法里,不再只传递计数器的字符串形式,而是把"Hello World "和计数器数值拼接后再设置给TextView,这是解决问题的核心。
布局文件检查提醒
确保你的activity布局(通常是activity_main.xml)有正确的控件配置:
- 一个id为
text_view_counter的TextView(如果代码里用了其他id,要保持一致) - 一个设置了
android:onClick="updateCounter"的Button,用来关联代码中的点击方法
这样调整后,每次点击按钮,TextView就会显示"Hello World"加上当前计数器的数值,完全符合你的需求啦!
内容的提问来源于stack exchange,提问作者Victor Struggling

