1

我目前使用的是下面的代码,但这会在开始时生成一个随机数(定义为 d20),然后只要我单击按钮就调用该数字。如何更改它以在单击按钮时生成该代码 (rndNumbers.nextInt(20) +1)。

我意识到其他人也问过类似的问题,但我没有看到它与我的完全相同(而且我几乎是一个初学者,所以我不太了解其他人的代码)。


import java.util.Random;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

Random rndNumbers = new Random(); 
int d20    = rndNumbers.nextInt(20) +1; 
Button roll;
TextView display;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    roll = (Button) findViewById(R.id.bRoll);
    display = (TextView) findViewById(R.id.tvDisplay);
roll.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                display.setText("The dice lands on " + d20);
            }
        });

        };



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
4

1 回答 1

0
    import java.util.Random;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

Random rndNumbers = new Random(); 
int d20    = rndNumbers.nextInt(20) +1; 
Button roll;
TextView display;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    roll = (Button) findViewById(R.id.bRoll);
    display = (TextView) findViewById(R.id.tvDisplay);
roll.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
d20    = rndNumbers.nextInt(20) +1; 
                display.setText("The dice lands on " + d20);
            }
        });

        };



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
于 2013-06-09T15:31:29.847 回答