我们可以从另一个函数调用OnCreate()方法吗?

时间:2016-12-30 18:29:59

标签: android android-studio oncreate

我正在制作一个简单的“猜数字应用”。应用程序在启动时会在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);
    }
}

1 个答案:

答案 0 :(得分:0)

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