2013-06-11 178 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