2013-06-11 174 views
-1

任何人都可以幫忙嗎?我需要生成一個隨機數,然後隨機數發生器,android

public class MainActivity extends Activity implements OnClickListener { 

    TextView tv1; 
    Button bt1; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     bt1 = (Button) findViewById(R.id.button1); 
     bt1.setOnClickListener(this); 
     tv1 =(TextView) findViewById(R.id.textView1); 
    } 

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

    @Override 
    public void onClick(View v) { 
     switch(v.getId()){ 
      case R.id.button1: 
       Random r = new Random(); 
       int i1=r.nextInt(80-65) + 65; 
       tv1 = (TextView) findViewById(R.id.textView1); 
       tv1.setText(i1); 
       break;}; 
     } 
    } 

然後它按下按鈕後關閉應用程序。

+0

你在日誌文件中看到了什麼('CatLog') – ashes999

回答

3

變化

tv1.setText(i1); 

tv1.setText(String.valueOf(i1)); 

tv1.setText(i1);你正在尋找一個字符串ID i1,裏面string.xml。那id可能不存在,並會導致崩潰ResourcesNotFoundException

編輯:tv1 = (TextView) findViewById(R.id.textView1);內onClick是沒用的,因爲你在onCreate內執行相同的初始化。您也可以在onCreate中移動Random r = new Random();。當然,你必須保留r作爲類成員

+0

'tv1 =(TextView)findViewById(R.id.textView1)';初始化每次點擊按鈕都可以被刪除,可能這個'Random r = new Random()';可以移動到按鈕外點擊 – Raghunandan

+0

@拉金丹丹你說得對 – Blackbelt

+0

我剛剛提到過,所以你可以添加它也作爲你的答案的一部分。順便說一下,你是超快回答 – Raghunandan