I am tring to do a quiz app, there is a random flag and random 4 answers, one of them should be a correct answer and random 3.
For now I have only been able to random answers, but sometimes I have the same answer several times. Fails to random 3 different answers that will not repeat themselves and add to that the correct answer.
package com.example.guesstheflag;
import androidx.appcompat.app.AppCompatActivity;
ListView listView;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_game);
listView = findViewById(R.id.myList);
imageView = findViewById(R.id.imagernd);
MyAdapter myAdapter = new MyAdapter();
listView.setAdapter(myAdapter);
//rnd image
Random rndImg = new Random();
int img = rndImg.nextInt(flags.length);
imageView.setImageResource(flags[img]);
}
// functions for answers list
class MyAdapter extends BaseAdapter{
@Override
public int getCount() {
return 4;
}
@Override
public Object getItem(int i) {
return answers[i];
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater layoutInflater = getLayoutInflater();
View row = layoutInflater.inflate(R.layout.custom, null);
TextView textView = row.findViewById(R.id.myText);
Random rnd = new Random();
int name = rnd.nextInt(answers.length);
textView.setText(answers[name]);
return row;
}
}
}
2
Answers
You can use
Collections.shuffle
.At somewhere you want to shuffle the order of the ArrayList
answers
:To set answer text of
i
:To set flag image of
i
:The point is not to draw an index randomly but to shuffle the ArrayList itself.
Assumptions
flags
array is equal to the same index in theanswers
array.answers
array.Requirement
answers
array.Solution
You need to change your
MyAdapter
class to be as followsThan change the
onCreate
method to do the followingExplanation
Basically you need to ensure the following conditions
answers
array.In the above
MyAdapter
we create a function to generate the random options calledgenerateOptions
whenever this function is called it will generate the random number while ensuring the above conditions are met.I have extensively commented the code but if you need more clarity, feel free to comment.
Suggestions
startGame
class with a function likeSetupGame
which is called in theonCreate
or whenever the user taps "Start" or "Restart"