package com.mg.numbergenerator;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
import android.text.InputFilter;
import android.text.Spanned;
public class Main extends Activity {
EditText min;
EditText max;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Random r = new Random();
min = (EditText) findViewById (R.id.editText1);
max = (EditText) findViewById (R.id.editText2);
final TextView TextView1 = (TextView) findViewById(R.id.textView1);
final EditText et1 = (EditText) findViewById(R.id.editText1);
final EditText et2 = (EditText) findViewById(R.id.editText2);
Button gen = (Button) findViewById(R.id.button);
gen.setOnClickListener(new View.OnClickListener() {
@SuppressLint("NewApi") @Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int number = min + r.nextInt( max - min +1); //error HERE
TextView1.setText(String.valueOf(number));
}
});
}
@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;
}
}
答案 0 :(得分:3)
min = (EditText) findViewById (R.id.editText1);
min
是您正在对其进行数学运算的EdiTtext对象
int number = min + r.nextInt( max - min +1);
而是从editText获取文本。使用Integer.parseInt(min.getText().toString)
。
try
{
int minnumber = Integer.parseInt(min.getText().toString);
int maxnumber = Integer.parseInt(max.getText().toString);
// do operation with minnumber and maxnumber
int number = minnumber+ r.nextInt( maxnumber - minnumber +1);
}
catch(NumberFormatException e) // thrown if number entered in edittext is not int.
{
e.printStacktrace();
}
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
答案 1 :(得分:0)
你不能只对EditText进行数学运算,它只是一个放置一些值的容器。使用下面的代码从EditText中获取值。
int min_value= Integer.parseInt(min.getText().toString());
int max_value= Integer.parseInt(max.getText().toString());
然后使用此值计算数学运算。
int number = min_value +r.nextInt(max_value - min_value + 1 );