【问题标题】:How does it work, that when I always open the app, it run the method and not only when I click on run?它是如何工作的,当我总是打开应用程序时,它会运行该方法,而不仅仅是在我单击运行时?
【发布时间】:2021-02-21 18:30:38
【问题描述】:

我每次打开应用程序时都想要一个随机数,而不仅仅是当我按下“运行”时。我怎么做? 如果我关闭模拟器/三星上的应用程序并再次打开应用程序,这里总是有相同的报价。 当我在 Android Studio 中单击(重新)运行按钮时,它才会再次运行 Methode setQuote()

我该怎么办,当我打开我的应用程序时,这个方法总是运行?

这是我的代码:

public class MainActivity extends Activity {

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override`enter code here`
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setQuote();
}


@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void setQuote(){

    List<String> listQuotes= new ArrayList<>();
    listQuotes.add("Quote 1");
    listQuotes.add("Quote 2");
    listQuotes.add("Quote 3");
    listQuotes.add("Quote 4");

    int random = ThreadLocalRandom.current().nextInt(0, listQuotes.size()+ 1);
    
    String quote = listQuotes.get(random);
     
  
    TextView textview = findViewById(R.id.textView5);
    textview.setText(quote);
    textview.setGravity(Gravity.CENTER_HORIZONTAL);

}

【问题讨论】:

  • 旁注:listQuotes.size()+ 1 可以提高ArrayOutOfBundsException,保持listQuotes.size()
  • 实际上,您的确切代码对我有用,并且每次我重新打开应用程序时都会随机化文本。附言就像 Zain 所说,大小后的 +1 会抛出 IndexOutOfBoundsException
  • “如果我关闭模拟器/三星上的应用程序并再次打开应用程序,这里总是有相同的报价”。我假设您并没有真正关闭应用程序(不是单击返回),而是单击 HOME(旧导航栏上的“O”或向上滑动手势)。这将导致 Activity “暂停”和“停止”,但不会被销毁,因此不会调用 onCreate。

标签: java android android-studio mobile methods


【解决方案1】:

我建议你看看the Android Lifecycle

onCreate() 在 Activity 第一次启动时被调用,如果你离开并重新打开应用程序 onCreate() 可能不会再次被调用。相反,请查看 onStart 或 onResume 之类的方法。每次可见 Activity 时都会调用 onResume()。

所以只需尝试将 setQuote() 从 onCreate 移动到 onStart 或 onResume(您覆盖,与 onCreate 相同)

【讨论】:

  • 好的,我来仔细看看 Android 生命周期。我只是一个初学者...但是 onStart() 或 onResume() 也不起作用。
  • 它应该可以工作,您可以验证它们是否被 Log.d 调用 Btw 为什么您有 requiresApi?我看不到任何东西需要在你的方法的顶部
猜你喜欢
  • 2017-12-25
  • 2021-10-12
  • 2012-12-16
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 2017-12-09
  • 2013-09-19
  • 1970-01-01
相关资源
最近更新 更多