我正在制作一个简单的“猜数字应用程序”。该应用在启动时会使用onCreate()方法生成一个随机数。在单击按钮的方法上,我编写了一个代码,以便用户输入数字,如果数字正确,则程序应再次生成一个随机数。
但是,当我尝试从按钮的onClick方法再次调用onCreate()方法时,系统崩溃。您能帮我如何从函数调用此onCreate方法吗?我在下面发布我的代码。
package com.amit.higherolower;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int randomNumber;
public void guessGame(View view){
String message = "";
EditText userNumber = (EditText) findViewById(R.id.numberEditBox);
String userNumberText = userNumber.getText().toString();
int userNumberInt = Integer.parseInt(userNumberText);
System.out.println(randomNumber);
if(userNumberInt < randomNumber){
message = "You've Guessed Lower";
((EditText) findViewById(R.id.numberEditBox)).setText("");
}
else if (userNumberInt > randomNumber){
message = "You've Guessed Higher";
((EditText) findViewById(R.id.numberEditBox)).setText("");
}
else{
message = "You're Right Dude, Now let's guess the new number again.";
onCreate(new Bundle());
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random randomGenerator = new Random();
randomNumber = randomGenerator.nextInt(9);
}
}
https://stackoverflow.com/a/7150118/5353361有正确的想法,请从中重构onClose
。具体地说,正如Umarov所说,将您的两行非样板代码带到另一个函数,然后调用它。
我也尝试过类似的东西:
public static void triggerRebirth(Context context, Intent nextIntent) {
Intent intent = new Intent(context, YourClass.class);
intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(KEY_RESTART_INTENT, nextIntent);
context.startActivity(intent);
if (context instanceof Activity) {
((Activity) context).finish();
}
Runtime.getRuntime().exit(0);
}
来自(https://github.com/JakeWharton/ProcessPhoenix)和https://stackoverflow.com/a/22345538/5353361
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句