我正在尝试做一个计算器应用程序(学校项目),所以我需要一个TextView来显示数字。因为这是我的第一个java项目,我想开始创建一个计数器,显示按钮被点击的次数(只是为了学习如何使用TextViews)。我的问题是,在第一次更新TextView后(当它显示“1”时),当我第二次按下按钮时,它会让我崩溃。
我的代码:
MainActivity.java
public class MainActivity extends AppCompatActivity {
public Integer number = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.no1);
ImageButton button = (ImageButton) findViewById(R.id.zeroB);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
number++;
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.no1);
tv.setText(number.toString());
}
});
}
...
content_main.xml
...
<TextView
android:layout_width="172dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/no1"
android:layout_gravity="left|top"
android:editable="true" />
...
答案 0 :(得分:1)
将您的代码修改为:
public class MainActivity extends AppCompatActivity {
public Integer number = 0;
//i would use this instead of the above
private int number = 0;
private TextView tv;
private ImageButton button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.no1);
button = (ImageButton) findViewById(R.id.zeroB);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
number++;
tv.setText(String.valueOf(number));
}
});
}
...