【问题标题】:Can we Call OnCreate() method from another function我们可以从另一个函数调用 OnCreate() 方法吗
【发布时间】:2016-12-30 18:29:58
【问题描述】:

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

【问题讨论】:

  • 只需创建另一个方法并将您的Random randomGenerator = new Random();randomNumber = randomGenerator.nextInt(9); 放入其中。并调用该方法。
  • @Umarov 作为答案发布,我也认为这是最好的解决方案

标签: android android-studio oncreate


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多