I have a quiz app that is working properly, but the thing is the user must answer all questions correctly in order to win the game(if the player gets it wrong the game will be over) .
What I wanted to do is have the questions answered and then at the end there will be an activity that will show how many the player has answered then there will be the options to retry and go back to menu
This is the code for the maingameactivity
public class MainGameActivity extends AppCompatActivity {
FButton buttonA, buttonB, buttonC, buttonD;
TextView questionText, triviaQuizText, timeText, resultText, coinText;
TriviaQuizHelper triviaQuizHelper;
TriviaQuestion currentQuestion;
List<TriviaQuestion> list;
int qid = 0;
int timeValue = 20;
int coinValue = 0;
CountDownTimer countDownTimer;
Typeface tb, sb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
//Initializing variables
questionText = (TextView) findViewById(R.id.triviaQuestion);
buttonA = (FButton) findViewById(R.id.buttonA);
buttonB = (FButton) findViewById(R.id.buttonB);
buttonC = (FButton) findViewById(R.id.buttonC);
buttonD = (FButton) findViewById(R.id.buttonD);
triviaQuizText = (TextView) findViewById(R.id.triviaQuizText);
timeText = (TextView) findViewById(R.id.timeText);
resultText = (TextView) findViewById(R.id.resultText);
coinText = (TextView) findViewById(R.id.coinText);
//Setting typefaces for textview and buttons - this will give stylish fonts on textview and button etc
tb = Typeface.createFromAsset(getAssets(), "fonts/TitilliumWeb-Bold.ttf");
sb = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
triviaQuizText.setTypeface(sb);
questionText.setTypeface(tb);
buttonA.setTypeface(tb);
buttonB.setTypeface(tb);
buttonC.setTypeface(tb);
buttonD.setTypeface(tb);
timeText.setTypeface(tb);
resultText.setTypeface(sb);
coinText.setTypeface(tb);
//Our database helper class
triviaQuizHelper = new TriviaQuizHelper(this);
//Make db writable
triviaQuizHelper.getWritableDatabase();
//It will check if the ques,options are already added in table or not
//If they are not added then the getAllOfTheQuestions() will return a list of size zero
if (triviaQuizHelper.getAllOfTheQuestions().size() == 0) {
//If not added then add the ques,options in table
triviaQuizHelper.allQuestion();
}
//This will return us a list of data type TriviaQuestion
list = triviaQuizHelper.getAllOfTheQuestions();
//Now we gonna shuffle the elements of the list so that we will get questions randomly
Collections.shuffle(list);
//currentQuestion will hold the que, 4 option and ans for particular id
currentQuestion = list.get(qid);
//countDownTimer
countDownTimer = new CountDownTimer(22000, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to timeText
timeText.setText(String.valueOf(timeValue) + "\"");
//With each iteration decrement the time by 1 sec
timeValue -= 1;
//This means the user is out of time so onFinished will called after this iteration
if (timeValue == -1) {
//Since user is out of time setText as time up
resultText.setText(getString(R.string.timeup));
//Since user is out of time he won't be able to click any buttons
//therefore we will disable all four options buttons using this method
disableButton();
}
}
//Now user is out of time
public void onFinish() {
//We will navigate him to the time up activity using below method
timeUp();
}
}.start();
//This method will set the que and four options
updateQueAndOptions();
}
public void updateQueAndOptions() {
//This method will setText for que and options
questionText.setText(currentQuestion.getQuestion());
buttonA.setText(currentQuestion.getOptA());
buttonB.setText(currentQuestion.getOptB());
buttonC.setText(currentQuestion.getOptC());
buttonD.setText(currentQuestion.getOptD());
timeValue = 20;
//Now since the user has ans correct just reset timer back for another que- by cancel and start
countDownTimer.cancel();
countDownTimer.start();
//set the value of coin text
coinText.setText(String.valueOf(coinValue));
//Now since user has ans correct increment the coinvalue
coinValue++;
}
//Onclick listener for first button
public void buttonA(View view) {
//compare the option with the ans if yes then make button color green
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
//Check if user has not exceeds the que limit
if (qid < list.size() - 1) {
//Now disable all the option button since user ans is correct so
//user won't be able to press another option button after pressing one button
disableButton();
//Show the dialog that ans is correct
correctDialog();
}
//If user has exceeds the que limit just navigate him to GameWon activity
else {
gameWon();
}
}
//User ans is wrong then just navigate him to the PlayAgain activity
else {
gameLostPlayAgain();
}
}
//Onclick listener for sec button
public void buttonB(View view) {
if (currentQuestion.getOptB().equals(currentQuestion.getAnswer())) {
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for third button
public void buttonC(View view) {
if (currentQuestion.getOptC().equals(currentQuestion.getAnswer())) {
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for fourth button
public void buttonD(View view) {
if (currentQuestion.getOptD().equals(currentQuestion.getAnswer())) {
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//This method will navigate from current activity to GameWon
public void gameWon() {
Intent intent = new Intent(this, GameWon.class);
startActivity(intent);
finish();
}
//This method is called when user ans is wrong
//this method will navigate user to the activity PlayAgain
public void gameLostPlayAgain() {
Intent intent = new Intent(this, PlayAgain.class);
startActivity(intent);
finish();
}
//This method is called when time is up
//this method will navigate user to the activity Time_Up
public void timeUp() {
Intent intent = new Intent(this, Time_Up.class);
startActivity(intent);
finish();
}
//If user press home button and come in the game from memory then this
//method will continue the timer from the previous time it left
#Override
protected void onRestart() {
super.onRestart();
countDownTimer.start();
}
//When activity is destroyed then this will cancel the timer
#Override
protected void onStop() {
super.onStop();
countDownTimer.cancel();
}
//This will pause the time
#Override
protected void onPause() {
super.onPause();
countDownTimer.cancel();
}
//On BackPressed
#Override
public void onBackPressed() {
Intent intent = new Intent(this, HomeScreen.class);
startActivity(intent);
finish();
}
//This dialog is show to the user after he ans correct
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(MainGameActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
//Since the dialog is show to user just pause the timer in background
onPause();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
FButton buttonNext = (FButton) dialogCorrect.findViewById(R.id.dialogNext);
//Setting type faces
correctText.setTypeface(sb);
buttonNext.setTypeface(sb);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//it will increment the question number
qid++;
//get the que and 4 option and store in the currentQuestion
currentQuestion = list.get(qid);
//Now this method will set the new que and 4 options
updateQueAndOptions();
//reset the color of buttons back to white
resetColor();
//Enable button - remember we had disable them when user ans was correct in there particular button methods
enableButton();
}
});
}
//This method will make button color white again since our one button color was turned green
public void resetColor() {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
}
//This method will disable all the option button
public void disableButton() {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
}
//This method will all enable the option buttons
public void enableButton() {
buttonA.setEnabled(true);
buttonB.setEnabled(true);
buttonC.setEnabled(true);
buttonD.setEnabled(true);
}
}
Edited
Just remove the wrapper if else inside all the buttons better to keep it as, don't repeat the code. I am assuming the screen that shows result is handled inside gameWon and you have implemented functionality for inCorrectDialog
public void buttonA(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonB(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonC(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonD(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonPressed(Button button) {
button.setButtonColor(ContextCompat.getColor(getApplicationContext(), R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
correctDialog();
} else {
inCorrectDialog();
}
} else {
gameWon();
}
}
Related
I would like to know how to set an if else condition where the next button have to be disabled if none of the buttons are being clicked. Otherwise, they are able to proceed to next question?
private AdvancedQuestion nAdvancedQuestion = new AdvancedQuestion();
private TextView nScoresView;
private TextView nQuestionsView;
private TextView tvTime;
private Button nButtonChoices1;
private Button nButtonChoices2;
private Button nButtonChoices3;
private Button nButtonChoices4;
private String nAnswers;
private int nScores = 0;
private int nQuestionNumbers = 0;
Button btnNextz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_quiz);
updateQuestions();
nButtonChoices1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (nButtonChoices1.getText() == nAnswers) {
correctSound.start();
nScores = nScores + 1;
nButtonChoices1.setEnabled(false);
nButtonChoices2.setEnabled(false);
nButtonChoices3.setEnabled(false);
nButtonChoices4.setEnabled(false);
nButtonChoices1.getBackground().setColorFilter(Color.GREEN, PorterDuff.Mode.MULTIPLY);
Toast.makeText(advancedQuiz.this, "correct", Toast.LENGTH_SHORT).show();
} else {
wrongSound.start();
Toast.makeText(advancedQuiz.this, "wrong", Toast.LENGTH_SHORT).show();
nButtonChoices1.setEnabled(false);
nButtonChoices2.setEnabled(false);
nButtonChoices3.setEnabled(false);
nButtonChoices4.setEnabled(false);
}
}
});
btnNextz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextSound.start();
updateQuestions();
nButtonChoices1.setEnabled(true);
nButtonChoices2.setEnabled(true);
nButtonChoices3.setEnabled(true);
nButtonChoices4.setEnabled(true);
nButtonChoices1.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
nButtonChoices2.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
nButtonChoices3.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
nButtonChoices4.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
}
private void updateQuestions() {
nQuestionsView.setText(nAdvancedQuestion.getQuestions(nQuestionNumbers));
nButtonChoices1.setText(nAdvancedQuestion.getChoices1(nQuestionNumbers));
nButtonChoices2.setText(nAdvancedQuestion.getChoices2(nQuestionNumbers));
nButtonChoices3.setText(nAdvancedQuestion.getChoices3(nQuestionNumbers));
nButtonChoices4.setText(nAdvancedQuestion.getChoices4(nQuestionNumbers));
nAnswers = nAdvancedQuestion.getCorrectAnswers(nQuestionNumbers);
nQuestionNumbers++;
}
private void updateScore(int points) {
nScoresView.setText("" + nScores);
}
Please note there is 4 possible answers. If none of them are selected, they cannot proceed to the next question until one button is press so they can go to the next question. The updateQuestions() is the part where i believe it will show next question.
This is a simple example on how to disable/enable a button based on an if condition -
int count = 0;
if (count == 0) {
NextButton.setEnabled(false);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.otherButtons:
count++;
NextButton.setEnabled(true);
Toast.makeText(this, "Button Disabled", Toast.LENGTH_LONG).show();
break;
case R.id.nextButton:
//Move the user to the next question
break;
}
}
Also check out this link
You will need to add a button element in the view of the activity you want it to appear on, then add an event listener to it either in the activity code or specify which function to call on click in the activities XML layout file.
See: https://developer.android.com/reference/android/widget/Button.html
Any idea how to illustrate backspace funtion in this code? I try to make some changes but it can't work the backspace function. So, i would like to help me, with the backspace button.
enter code here
public class MainActivity extends AppCompatActivity implements OnClickListener {
private TextView mCalculatorDisplay;
private Boolean userIsInTheMiddleOfTypingANumber = false;
private CalculatorBrain mCalculatorBrain;
private static final String DIGITS = "0123456789.";
DecimalFormat df = new DecimalFormat("############");
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide the status bar and other OS-level chrome
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCalculatorBrain = new CalculatorBrain();
mCalculatorDisplay = (TextView) findViewById(R.id.textView1);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(8);
findViewById(R.id.button0).setOnClickListener(this);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
findViewById(R.id.button7).setOnClickListener(this);
findViewById(R.id.button8).setOnClickListener(this);
findViewById(R.id.button9).setOnClickListener(this);
findViewById(R.id.buttonBackspace).setOnClickListener(this);
findViewById(R.id.buttonAdd).setOnClickListener(this);
findViewById(R.id.buttonSubtract).setOnClickListener(this);
findViewById(R.id.buttonMultiply).setOnClickListener(this);
findViewById(R.id.buttonDivide).setOnClickListener(this);
findViewById(R.id.buttonToggleSign).setOnClickListener(this);
findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
findViewById(R.id.buttonEquals).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
// The following buttons only exist in layout-land (Landscape mode) and require extra attention.
// The messier option is to place the buttons in the regular layout too and set android:visibility="invisible".
if (findViewById(R.id.buttonSquareRoot) != null) {
findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
}
if (findViewById(R.id.buttonSquared) != null) {
findViewById(R.id.buttonSquared).setOnClickListener(this);
}
if (findViewById(R.id.buttonInvert) != null) {
findViewById(R.id.buttonInvert).setOnClickListener(this);
}
if (findViewById(R.id.buttonSine) != null) {
findViewById(R.id.buttonSine).setOnClickListener(this);
}
if (findViewById(R.id.buttonCosine) != null) {
findViewById(R.id.buttonCosine).setOnClickListener(this);
}
if (findViewById(R.id.buttonTangent) != null) {
findViewById(R.id.buttonTangent).setOnClickListener(this);
}
}
#Override
public void onClick (View v) {
String buttonPressed = ((Button) v).getText().toString();
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
// ERROR PREVENTION
// Eliminate entering multiple decimals
} else {
mCalculatorDisplay.append(buttonPressed);
}
} else {
if (buttonPressed.equals(".")) {
// ERROR PREVENTION
// This will avoid error if only the decimal is hit before an operator, by placing a leading zero
// before the decimal
mCalculatorDisplay.setText(0 + buttonPressed);
} else {
mCalculatorDisplay.setText(buttonPressed);
}
}
userIsInTheMiddleOfTypingANumber = true;
}else{
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
mCalculatorBrain.performOperation(buttonPressed);
if (new Double(mCalculatorBrain.getResult()).equals(0.0)) {
mCalculatorDisplay.setText("" + 0);
} else {
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", mCalculatorBrain.getResult());
outState.putDouble("MEMORY", mCalculatorBrain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
mCalculatorBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
mCalculatorBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
if (new Double(mCalculatorBrain.getResult()).equals(0.0)){
mCalculatorDisplay.setText("" + 0);
} else {
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
}
In your layout you can add a onClick attribute to each button, say onClick="function", and in your activity you just need to implement a method like this:
public void function(View v) {
switch(v.getId()) {
case R.id.buttonBackspace:
// handle the backspace button
break;
case R.id.xxx:
// handle the button
break;
...
}
}
And for digits, I suggest assign a tag to each digit button in the layout, and do your logic in java based on the tag, instead of the text on the button. Because the text is just a UI, it might change in the future due to other possible requirements.
Hello as the title state I'm trying to setup a next and previous buttons but I'm still new at coding so this has me a little confused.
I tried to use if statements with an enum within a single button but it defaults to last if statement when the event is handled here's the code-
private enum EVENT{
pe1, pe2, pe3, pe4;
}
EVENT currentEvent = EVENT.pe1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentEvent==EVENT.pe1) {
olText.setText("PE1");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe2;
}
if (currentEvent==EVENT.pe2){
olText.setText("PE2");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe3;
}
}
});
}
I tried to use the enumerator to assign a number to each if statement so when the user hit previous it would subtract and when they hit next it would add, each number would have some text or image within its if statement but as I said it defaults to the last if statement- Any help is much appreciated.
How about this?
int eventNum = 0;
int maxEvents = XXX;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
prevBtn = (Button) findViewById(R.id.prevBtn);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
setEventData(true);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(prevBtn) && eventNum > 0) {
eventNum--;
setEventData(false);
return;
}
if(v.equals(nextBtn) && eventNum < maxEvents - 1) {
eventNum++;
setEventData(true);
return;
}
}
}
nextBtn.setOnClickListener(listener);
prevBtn.setOnClickListener(listener);
}
private void setEventData(boolean animLeft) {
olText.setText("PE" + (eventNum + 1));
if(animLeft) {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
} else {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_right));
}
}
You'll want to create a class variable that keeps track of which text your TextView is showing. So in the following example, I create a list of Strings that I just store in a String array. Then I create an iterator variable which stores which String from the list I'm currently viewing in the TextView. Every time you click the previous or next button, you simply store your current state in the iterator variable so you can recall it the next time a click event comes in.
String[] labels = {"one", "two", "three", "four"};
int currentView = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onPreviousButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView--; //decrement our iterator
if(currentView < 0) currentView = 0; //check to make sure we didn't go below zero
textView.setText(labels[currentView]);
}
public void onNextButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView++; //increment our iterator
if(currentView > labels.length-1) currentView = labels.length-1; //check to make sure we didn't go outside the array
textView.setText(labels[currentView]);
}
I'm making a quiz app. User has to finish the phrase shown on display and write the name of the car in the edittext, after pushing on button, if the answer right, edittext become green, if doesn't, become red. If all answers right (green), intent move on next activity.
I have some difficulties with if statement edit text become red even the answer was right. Also how to make INTENT to move on next activity if all right, if not it doesn't move?
public class MainActivity extends AppCompatActivity {
EditText et_one_one, et_one_two, et_one_three;
Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_one_one = (EditText) findViewById(R.id.et_one_one);
et_one_two = (EditText) findViewById(R.id.et_one_two);
et_one_three = (EditText) findViewById(R.id.et_one_three);
final String t1 = et_one_one.getText().toString();
final String t2 = et_one_two.getText().toString();
final String t3 = et_one_three.getText().toString();
buttonCheck = (Button) findViewById(R.id.buttonCheck);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
et_one_three.setBackgroundColor(Color.RED);
}
}
});
}
}
You're changing the color of just the et_one_one each time in your if else statements. Shouldn't it be for different edittexts?
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean allAnswersCorrect = true;
String t1 = et_one_one.getText().toString();
String t2 = et_one_two.getText().toString();
String t3 = et_one_three.getText().toString();
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
allAnswersCorrect = false;
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_three.setBackgroundColor(Color.RED);
}
if(allAnswersCorrect){
Intent intent = new Intent(YourActivity.this, YourSecondActivity.class);
startActivity(intent);
}
}
});
Maintain a allAnswersCorrect boolean to check whether your answers are correct or not. If all are correct the move to your next activity.
You should use t2.equals("maserati"), and it will be ok.
This is the first time I'm ever dabbling in Android development so please bear with me.
My requirement is this:
I have two buttons on screen, A and B. If the user presses both buttons (order doesn't matter), I need another page to be displayed. Pressing either A or B should do nothing.
Is this possible? If so, how would I achieve this?
Thank you.
This is possible if you take a flag. (boolean)
You should set a flag in your button listeners.
public class Mtest extends Activity {
Button b1;
Button b2;
boolean flag_1 = false;
boolean flag_2 = false;
public void onCreate(Bundle savedInstanceState) {
...
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(myhandler1);
b2.setOnClickListener(myhandler2);
}
View.OnClickListener myhandler1 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 1st button
flag_1 = true;
doSomething();
}
};
View.OnClickListener myhandler2 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 2nd button
flag_2 = true;
doSomething();
}
};
}
public void doSomething(){
if(flag_1 && flag_2)
{
//DO SOMETHING
}
}
}
Create two boolean's like button1isClickedand button2isClicked,then set an onClickListener for each Button. When the the Button is clicked set the value of these two boolean's to true, then simply create an if() statement that will chekc to see if both buttons have been clicked, like this:
if(button1isClicked == true && button2isClicked == true){
//display your new page
}