[英]I have around 1000 different activities in my Android App. How can I jump to a random activity?
Intent myIntent = new Intent(this,Q1.class);
In my app I have 1000 different activities namely Q1,Q2,Q3....Q1000.在我的应用程序中,我有 1000 个不同的活动,即 Q1、Q2、Q3....Q1000。 I have a button on each activity and I want when a user clicks on it, he should land on some random activity.
我在每个活动上都有一个按钮,我希望当用户点击它时,他应该登陆一些随机活动。 How to achieve this ?
如何实现这一目标?
Although this is terrible, I'll still show a possible way to do this.虽然这很糟糕,但我仍然会展示一种可能的方法来做到这一点。 But just remember, this is TERRIBLE .
但请记住,这太可怕了。
You can store all the activity classes in an ArrayList
.您可以将所有活动类存储在
ArrayList
。
ArrayList<Class<Activity>> activities = new ArrayList<> ();
And then you add all the activities into the ArrayList
.然后将所有活动添加到
ArrayList
。 Yeah, I know, this part is tedious.是的,我知道,这部分很乏味。 For example,
例如,
activities.add (Activity1.class);
And then you create a Random
called rand
and use that to access an element in the list:然后创建一个名为
rand
的Random
并使用它来访问列表中的元素:
list.get (rand.nextInt (list.size()));
Here is another "better" way to do it, but it's still kinda bad.这是另一种“更好”的方法,但它仍然有点糟糕。 I strongly advise you to store teh questions in a database.
我强烈建议您将问题存储在数据库中。 Anyway, here's the better-but-still-bad method.
无论如何,这是更好但仍然很糟糕的方法。
You create a question class:您创建一个问题类:
public class Question {
//here you can put correctAnswer, questionText etc
}
After that, you make an ArrayList
of Question
s ie ArrayList<Question>
.之后,您创建一个
Question
的ArrayList
,即ArrayList<Question>
。
ArrayList<Question> questions = new ArrayList<> ();
And still, you need to add 1000 questions to the array list.而且,您仍然需要将 1000 个问题添加到数组列表中。 Then you can just use a
Random
to access it.然后你可以使用
Random
来访问它。
When you want to display a question in one activity, you can just putExtra
in Intent
before starting the activity.当你想在一个活动中显示一个问题时,你可以在开始活动之前在
Intent
putExtra
的内容。 putExtra
basically passes some "parameter" thingys to the activity. putExtra
基本上将一些“参数”东西传递给活动。 Then in the activity, you can just get the "Extra" and use the Question
object to display.然后在活动中,您可以直接获取“额外”并使用
Question
对象来显示。 eg set the text of a TextView
to the question text.例如,将
TextView
的文本设置为问题文本。
this can be also used:这也可以使用:
try {
Random rand=new Random();
Intent i = new Intent(this, Class.forName("test.hu.test.Q"+rand.nextInt(1000)+"")); // get activity's class by reflection
startActivity(i);
}catch (Exception e)
{
}
But i also suggest to use DB.但我也建议使用 DB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.