如何使用TextView方法输出整数?

时间:2015-06-10 01:51:13

标签: java android xml

我想输出一个始终在活动中的随机数! 这是我的代码,问题在哪里?

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fourth);
    OnClickButtonListener();
    textBox.setText("" + randomInt);


}
double randNumber = Math.random();
int d = (int) (randNumber * 100 );


int randomInt = (int)d * 2;

TextView textBox = (TextView) findViewById(R.id.textView8);

2 个答案:

答案 0 :(得分:1)

您需要在onCreate()方法中初始化TextView。您的代码看起来像这样

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fourth);
    TextView textBox = (TextView) findViewById(R.id.textView8);
    double randNumber = Math.random();
    int d = (int) (randNumber * 100 );      
    int randomInt = (int)d * 2;
    textBox.setText("" + randomInt);

}

答案 1 :(得分:0)

TextView textBox = (TextView) findViewById(R.id.textView8);移至onCreatesetContentView

之后