-4

I am creating a simple quiz app and I need when users put their name in the EditText pop up a Toast message said "GoodLuck"+ Name.Could someone help on this? Here is my code: Thanks a lot!

MainActivity.java

 public class MainActivity extends AppCompatActivity {

        String Name;
        int score = 0;
        Button submitButton;
        Button resetButton;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            //user input name
             final EditText nameField = (EditText)findViewById(R.id.nameField);
              Name = nameField.getText().toString();

            //submitButton shows user score
            submitButton = (Button) findViewById(R.id.submitButton);
            submitButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    submitButton.setText("Your score is:" + score);
                }
            });
            //resetButton reset score to 0
            resetButton = (Button) findViewById(R.id.resetButton);
            resetButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    submitButton.setText((String.valueOf(0)));
                }
            });
        }

activity_main.xml

 <EditText
            android:id="@+id/nameField"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif-light"
            android:inputType="text"
            android:hint="Name"
            android:textColor="#EF6C00"
            android:textSize="15sp"/>
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
Eleni_M
  • 3
  • 7

2 Answers2

0

User should press Enter button after finsihed typing his name.

editText.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                if (event.getAction() == KeyEvent.ACTION_DOWN
                        && event.getKeyCode() ==       KeyEvent.KEYCODE_ENTER) 
                {
                   Toast.makeText(getApplicationContext(), "Good Luck:"+editText.getText().toString(), Toast.LENGTH_SHORT).show();    
                    return false;
                } 

            return false;
        }
    });

If you dont want to force user to press Enter button. Then use one button to updte name. Once user click on the button you can popup Toast.

Shiv Buyya
  • 3,770
  • 2
  • 30
  • 25
0

Add this line of code in submit button click

 Toast.makeText(getApplicationContext(), "GoodLuck " +Name , Toast.LENGTH_SHORT).show();
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154