Java 如何使按钮转到另一个随机活动

Java 如何使按钮转到另一个随机活动,java,android,Java,Android,我想让一个按钮转到一个随机活动,我目前正在使用意图打开活动,你还能这样做吗。另外,我使用android studio只是为了说明这一点。我用的是java而不是kotlin这是我的第一个应用程序,仅此而已 我的xml是 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:t

我想让一个按钮转到一个随机活动,我目前正在使用意图打开活动,你还能这样做吗。另外,我使用android studio只是为了说明这一点。我用的是java而不是kotlin这是我的第一个应用程序,仅此而已

我的xml是

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#B13801FF"
tools:context=".MainActivity">

<TextView
    android:layout_width="282dp"
    android:layout_height="230dp"
    android:layout_centerInParent="true"
    android:text='"The greatest degree of inner tranquility comes from the development of love and compassion. The more we care for the happiness of others, the greater is our own sense of well-being." —Tenzin Gyatso' />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Next Quote (2)" />


</RelativeLayout>

如果我是正确的,您希望随机打开一个活动。 为此,您可以创建从0到n(活动数量)的随机数,然后创建一个方法,并将其中一个数字作为参数传递给该方法

void openRandomActivity(int number){
   Intent i = null;
   if(number == 1) {
      i = new Intent(this, Activity1.class);
   } else if(number == 2) {
      i = new Intent(this, Activity2.class);
   } else ... {
      //Repeat n times, where n is quantity of activities
      ...
   }
   startActivity(i)
}

//in onCreate
 openRandomActivity((new Random()).nextInt(5))
//5 is quantity of activities
或者,您可以创建类对象列表(Activity.Class、Activity2.Class,…),随机选择该列表类对象中的一个项,并将其传递给方法参数。 代码如下所示:

//In onCreate
List<Class> activities = Arrays.asList(Activity1.class, Activity2.class, ...)
Class randomClass = activities.get((new Random()).nextInt(activities.size()));
openRandomActivity(randomClass);

void openRandomActivity(Class class){
   Intent i = new Intent(this, class):
   startActivity(i)
}
要从Activity3获取该文本:

Intent intent = getIntent();
String text = intent.getStringExtra("text");
myButton3.setText(text);

你的问题不清楚,你面临的问题是什么?@ashrafalshawhy我想让一个按钮转到随机活动你说的“转到随机活动”是什么意思?@ashrafalshawhy我想让一个按钮转到非预定活动activity@AshrafAlshahawy或者,如果这有帮助的话,我想要一个按钮转到许多未预先确定的活动之一
Intent i = new Intent(this, Activity3.class);
i.putExtra("text", myButton.getText().toString());
startActivity(i);
Intent intent = getIntent();
String text = intent.getStringExtra("text");
myButton3.setText(text);