Android SDK ( Eclipse) : Typing Game ,How to Creat

2019-04-16 20:47发布

问题:

First of all I'm Totally New To Android , Started Learning a week ago , so please be patient

second : I have a simple Typing Game that when you write a text inside the editText , it will compare it with the TextView above it and give you a dialog if the written text exactly the same or not,give you the time you took to write it in seconds and save the best score !

Actually I have more than one Thing to ask you guys about in this app,but the main thing is to make the app gives random sentences every time the user plays using an Array !

The other Stuff I Need to know listed below ,So thankful if you could help me in this too :

1- Create an AlertDialog When The then The EditText is empty with a resume Button , When the Dialog Shows , the Timer will Stop , when the user press resume button the timer will resume running normally and continue Playing !

2- I noticed a logical error in my EditText , Like when I press Enter the text will give a new line and after 3 or 4 times the layout will get ugly and messed up , I already limited the characters of it but I don't Know how to stop it from creating new Lines and messes up my App ..

3- I want to Disable the Enter Button in the softKeyboard while typing in the EditText ,and Actually want it to Link it with the Submit Button , like when user click it,it will automatically press the Submit Button rather than giving new lines and for faster writing !

**Here is The App Layout**

Here Is The MainActivity Code :

  public class MainActivity extends Activity {

  private int Lowest = 0;

  private static String File = "Best Score";

  Button   w;

  Button   q;

  TextView t;

  TextView b;

  TextView s;

  EditText e;

  private Timer ti;    //Timer object Initialization

  private int TimeCounter = 0; // Timer Initialization

  SharedPreferences BestScore ;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  w = (Button) findViewById(R.id.Submit);      // Referring Write Button By Id 

  q = (Button) findViewById(R.id.QuitGame);     // Referring Quit By Id 

  b = (TextView) findViewById(R.id.BestTimer);

  t = (TextView) findViewById(R.id.World);      // Referring TextView By Id 

  s = (TextView) findViewById(R.id.Seconds);

  e = (EditText) findViewById(R.id.Text); // Referring EditText By Id 

  e.setHint("Touch here to write ");

  BestScore = getSharedPreferences(File , 0);

  String LoadBestScore = BestScore.getString("Best Score", "000");

  int LoadNewMin = BestScore.getInt("New MInimum" , 000);

  Lowest = LoadNewMin;

  b.setText(LoadBestScore);  

  //Lunch Dialog Creation 

  AlertDialog.Builder d0 = new AlertDialog.Builder(this);

  d0.setTitle("Start Game");

  d0.setCancelable(false);

  d0.setMessage("Are you ready?");

  d0.setNegativeButton("No",new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

  finish();

  }

  });

  d0.setPositiveButton("Yes",new DialogInterface.OnClickListener() {

  @Override   

  public void onClick(DialogInterface dialog, int which) {

  ti = new Timer();

  ti.scheduleAtFixedRate(new TimerTask() {

  @Override

  public void run() {

  // TODO Auto-generated method stub

  runOnUiThread(new Runnable() {

  public void run() {

  TimeCounter++;

  s.setText(String.valueOf(TimeCounter));

  }

  });

  }       

  }, 1000, 1000); 

  }

  });

  AlertDialog dx = d0.create();

  dx.show();


  //What Happens when Touching "Submit" Button 

  w.setOnClickListener(new View.OnClickListener() {

  @Override

  public void onClick(View v) {

  String check1 = t.getText().toString();

  String check2 = e.getText().toString();

  if (check1.equals(check2)){ // When The Written Text was Right 

  ti.cancel();//stopping the timer.

  if(Lowest== 0)

  {Lowest=TimeCounter; 

  b.setText(String.valueOf(Lowest));

  String SaveBest = b.getText().toString();

  SharedPreferences.Editor BestEditor = BestScore.edit();

  BestEditor.putString("Best Score",SaveBest);

  BestEditor.commit(); 

  int LowestNew = Lowest;

  SharedPreferences.Editor NewMin = BestScore.edit();

  NewMin.putInt("New MInimum", LowestNew );

  NewMin.commit();

  AlertDialog.Builder bs1 = new AlertDialog.Builder(MainActivity.this);

  bs1.setCancelable(false);

  bs1.setTitle("Success");


  bs1.setMessage("Congratualtions !!, You Broke The Best Score !!,It took you :"+ String.valueOf(TimeCounter)+" Seconds !");

  bs1.setNegativeButton("Quit Game",new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

  finish();

  }

  });

  bs1.setPositiveButton("Replay",new DialogInterface.OnClickListener() {

  @Override

   public void onClick(DialogInterface dialog, int which) {

   e.setText("");

   TimeCounter =0;       // Rest Timer when Replaying !

   ti = new Timer();        

   ti.scheduleAtFixedRate(new TimerTask() {

  @Override

  public void run() {

  // TODO Auto-generated method stub

  runOnUiThread(new Runnable() {

  public void run() {

  TimeCounter++;

  s.setText(String.valueOf(TimeCounter)); 

  }

  });

  }

  }, 1000, 1000); 

  }      

  });

  AlertDialog dx = bs1.create(); 

  dx.show();

  }      

  else  if (Lowest>TimeCounter ) 

  {b.setText(String.valueOf(TimeCounter));

  Lowest = TimeCounter;

  String SaveBest = b.getText().toString();

  SharedPreferences.Editor BestEditor = BestScore.edit();

  BestEditor.putString("Best Score",SaveBest);

  BestEditor.commit(); 

  int LowestNew = Lowest;

  SharedPreferences.Editor NewMin = BestScore.edit();

  NewMin.putInt("New MInimum", LowestNew );

  NewMin.commit();

  AlertDialog.Builder bs2 = new AlertDialog.Builder(MainActivity.this);

  bs2.setCancelable(false);

  bs2.setTitle("Success");

  bs2.setMessage("Congratualtions !!, You Broke The Best Score !!,It took you :"+ String.valueOf(TimeCounter)+" Seconds !");

  bs2.setNegativeButton("Quit Game",new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

  finish();

  }
  });
  bs2.setPositiveButton("Replay",new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

  e.setText("");

  TimeCounter =0;       // Rest Timer when Replaying !

  ti = new Timer();    

  ti.scheduleAtFixedRate(new TimerTask() {

  @Override

  public void run() {

  // TODO Auto-generated method stub

  runOnUiThread(new Runnable() {

  public void run() {

  TimeCounter++;

  s.setText(String.valueOf(TimeCounter));

  }

  });

  }

  else {

  AlertDialog.Builder d1 = new AlertDialog.Builder(MainActivity.this);

  d1.setCancelable(false);

  d1.setTitle("Success");

  d1.setMessage("You Wrote it Right , it took you :"+ String.valueOf(TimeCounter)+" Seconds !");

  d1.setNegativeButton("Quit Game",new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

  finish();

  }

  });

  d1.setPositiveButton("Replay",new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

  e.setText("");

  TimeCounter =0;       // Rest Timer when Replaying !
  ti = new Timer();               

  ti.scheduleAtFixedRate(new TimerTask() {

  @Override

  public void run() {

  // TODO Auto-generated method stub

  runOnUiThread(new Runnable() {

  public void run() {

  TimeCounter++;

  s.setText(String.valueOf(TimeCounter)); 


  }

  });

  }

  }, 1000, 1000);

  } 

  });

  }, 1000, 1000);

  }                                     
  });

  AlertDialog dx = bs2.create(); 

  dx.show(); 

  }  

  }}

  //When The Text Is Empty !

  else if (check2.equals(""))

  { Toast.makeText(MainActivity.this,"It's Empty ",Toast.LENGTH_LONG).show();}



  else  // When the Text Is Wrong !

  { 

  ti.cancel();

  AlertDialog.Builder d2 = new AlertDialog.Builder(MainActivity.this);

  d2.setCancelable(false);

  d2.setTitle("Failed");  d2.setMessage("You Wrote it Wrong !, Try agin ?");

  d2.setNegativeButton("Quit",new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

  // TODO Auto-generated method stub

  finish();

  }

  } );

  d2.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

  // TODO Auto-generated method stub

  e.setText("");

  TimeCounter = 0;

  ti = new Timer();  //Resting Timer !

  ti.scheduleAtFixedRate(new TimerTask(){

  @Override

  public void run() {

  // TODO Auto-generated method stub

  runOnUiThread(new Runnable() {

  public void run() {

  s.setText(String.valueOf(TimeCounter)); 

  TimeCounter++;

  }

  });

  }

  }, 1000, 1000);

  }

  });

  AlertDialog dx = d2.create();

  dx.show();

  }

  }});

  q.setOnClickListener(new View.OnClickListener() {

  @Override

  public void onClick(View v) {

  // TODO Auto-generated method stub

  finish();

  }

  });

  }

  @Override

  public boolean onCreateOptionsMenu(Menu menu) {

  // Inflate the menu; this adds items to the action bar if it is present.

  getMenuInflater().inflate(R.menu.main, menu);

  return true;

  }

  }

Here is The XML Code :

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

    <EditText
    android:id="@+id/Text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/Submit"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="58dp"
    android:maxLength="15"
    android:lines="1"
    android:ems="10"                     >
   <requestFocus />
   </EditText>

    <Button
    android:id="@+id/Submit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/Text"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="72dp"
    android:text="S U B M I T" />

    <TextView
    android:id="@+id/World"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/Text"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="67dp"
    android:text="Hello World"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/TimerView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="Timer :"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/BTSeconds"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/BestTimer"
    android:layout_alignParentRight="true"
    android:text="Secs"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView
    android:id="@+id/Seconds"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/BTSeconds"
    android:layout_alignBottom="@+id/BTSeconds"
    android:layout_toLeftOf="@+id/World"
    android:text="000"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/BestTimer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/TimerView"
    android:layout_alignBottom="@+id/TimerView"
    android:layout_toLeftOf="@+id/BTSeconds"
    android:text="000"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/BestView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/BestTimer"
    android:layout_alignBottom="@+id/BestTimer"
    android:layout_toLeftOf="@+id/BestTimer"
    android:text="Best :"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/TimerSeconds"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/Seconds"
    android:layout_alignBottom="@+id/Seconds"
    android:layout_alignLeft="@+id/World"
    android:text="Secs"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<Button
    android:id="@+id/QuitGame"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="29dp"
    android:layout_toRightOf="@+id/Seconds"
    android:text="Quit Game" />

For The "When Empty" Dialog and Pausing , I Just Wrote the AlertDialog for you Guys To modify it to make it pause and Resume , Here is the code :

  else if (check2.equals(""))      //When The Text Is Empty !

  {


  AlertDialog.Builder d3 = new AlertDialog.Builder(MainActivity.this);

  d3.setTitle(" Empty Text?");

  d3.setMessage("You Didn't Write Anything yet !");

  d3.setNegativeButton("Quit game",new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

  finish();

  }

  });

  d3.setPositiveButton("Resume",new DialogInterface.OnClickListener() {

  @Override

  public void onClick(DialogInterface dialog, int which) {

  ti.scheduleAtFixedRate(new TimerTask() {

  @Override

  public void run() {

  // TODO Auto-generated method stub

  runOnUiThread(new Runnable() {

  public void run() {

  TimeCounter++;

  s.setText(String.valueOf(TimeCounter)); 


  }

  });

  }

  }, 1000, 1000);                                               

  }

  });

  AlertDialog dx = d3.create();

  dx.show();

  }

I Know The Code is Long , I Really Appreciate Any help and please , use comments when writing codes so that I understand what u did cus I'm Still New to Android, Thanks For your Time !

回答1:

Set android:singleLine="true" to your edit text in layout

And in activity set onkeylistener which looks for enter key tobe pressed.

[YourEditTextObject].setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                if(arg1==KeyEvent.KEYCODE_ENTER){
                    //Do whatever you do on click of submit button

                }
                return false;
            }
        });