【发布时间】: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