我试图从一个编辑文本中获取一个int,将其设置为inputtype=“number”,然后将其输出(稍后我将处理它)我不能这样做,这是我被告知要尝试的代码,但它不起作用
Button go;
EditText num;
TextView OP, ST;
String OPS;
int oer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initalize();
go.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int myNum = 0;
OPS = num.getText().toString();
try {
myNum = Integer.parseInt(OPS);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
OP.setText(myNum);
}
在我运行它之后,强制关闭。
这是原木猫:
09-09 16:53:00.400: W/ResourceType(20145): No package identifier when getting value for resource number 0x00000008
09-09 16:53:00.400: D/AndroidRuntime(20145): Shutting down VM
09-09 16:53:00.400: W/dalvikvm(20145): threadid=1: thread exiting with uncaught exception (group=0x40a411f8)
09-09 16:53:00.561: E/AndroidRuntime(20145): FATAL EXCEPTION: main
09-09 16:53:00.561: E/AndroidRuntime(20145): android.content.res.Resources$NotFoundException: String resource ID #0x8
09-09 16:53:00.561: E/AndroidRuntime(20145): at android.content.res.Resources.getText(Resources.java:248)
09-09 16:53:00.561: E/AndroidRuntime(20145): at android.widget.TextView.setText(TextView.java:3473)
09-09 16:53:00.561: E/AndroidRuntime(20145): at com.Nutty.studios.randnumgen.free.RandomNumberGenActivity$1.onClick(RandomNumberGenActivity.java:42)
09-09 16:53:00.561: E/AndroidRuntime(20145): at android.view.View.performClick(View.java:3511)
09-09 16:53:00.561: E/AndroidRuntime(20145): at android.view.View$PerformClick.run(View.java:14105)
09-09 16:53:00.561: E/AndroidRuntime(20145): at android.os.Handler.handleCallback(Handler.java:605)
09-09 16:53:00.561: E/AndroidRuntime(20145): at android.os.Handler.dispatchMessage(Handler.java:92)
09-09 16:53:00.561: E/AndroidRuntime(20145): at android.os.Looper.loop(Looper.java:137)
09-09 16:53:00.561: E/AndroidRuntime(20145): at android.app.ActivityThread.main(ActivityThread.java:4575)
09-09 16:53:00.561: E/AndroidRuntime(20145): at java.lang.reflect.Method.invokeNative(Native Method)
09-09 16:53:00.561: E/AndroidRuntime(20145): at java.lang.reflect.Method.invoke(Method.java:511)
09-09 16:53:00.561: E/AndroidRuntime(20145): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
09-09 16:53:00.561: E/AndroidRuntime(20145): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
09-09 16:53:00.561: E/AndroidRuntime(20145): at dalvik.system.NativeStart.main(Native Method)
如果我尝试将字符串输出,但不将其作为整数,那么它可以正常工作吗?
最佳答案
1。您将永远无法从EditText获得int
,它提供了InputType
来为您提供正确的软键盘…
2。您可以使用此..int i = Integer.parseInt(editText.getText().toString());
此外,setText
希望您为它提供一个String
。所以你需要这么做…OP.setText(myNum+"");
toString()
只适用于Object
类型,正如您所声明的myNum
为int
,这是一个基元类型….您需要使用+ ""