简体   繁体   中英

Control flow in android studio from layout file to MainActivity.java

Below is a code snippet of an android application generating a random number form 1-20 and user guesses the number, when the button is pressed after guessing the number, the number written by the user (val) and generated by the app (rand_no) is compared.

After comparison I want the displayed text to disappear so that new output is generated every time when the guess is made and the button is pressed.

I set the visibility to INVISIBLE every time the function is called (when the button is pressed) and then again set the visibility to VISIBLE after comparison is made and output is to be displayed. But to my surprise the action happens only once and the text is no longer visible after first function call.

public class MainActivity extends AppCompatActivity {
Random random=new Random();
int rand_no=random.nextInt(20)+1;
public void function(View v)
{
    EditText e1=(EditText)findViewById(R.id.editText); //for text input by 
                                                       //the user

    TextView e2=(TextView) findViewById(R.id.textOutput); //for output text

    int val=Integer.parseInt(e1.getText().toString());

    e2.setVisibility(View.INVISIBLE);  //setting output to INVISIBLE
    if(rand_no<val)
    {
        e2.setText("Go Lower!");
    }

    if(rand_no>val)
    {
        e2.setText("Go Higher!");
    }

    if(rand_no==val)
    {
        e2.setText("You guessed right!");
    }
    e2.setVisibility(View.VISIBLE); //setting output to VISIBLE

      /* Fading away the output*/
    e2.animate().setStartDelay(2000);
    e2.animate().alpha(0).setDuration(1000);
}

Hence I want to know that after the function ends, the control passes again to layout file? Or it remains in MainActivity.java as it seems that visibility is assigned only once even if we press the button many times for the function to execute again again.

e2.animate().alpha(0).setDuration(1000);

You are fading it, so you need to make it visible again.

replace quoted line with below code

    e2.animate().alpha(0).setDuration(1000)
    .setListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {

        }

        @Override
        public void onAnimationEnd(Animator animation) {
            e2.animate().alpha(1).setDuration(500);
        }

        @Override
        public void onAnimationCancel(Animator animation) {

        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM