Toast将不会在android应用程序上显示,使用android studio

时间:2017-09-10 13:20:10

标签: java android

早上好,我试着让吐司显示学生人数是否小于0或大于100.该应用程序似乎工作正常,除了显示吐司。这项任务将于明天晚上到期。

这是我的代码:

package co.tekitall.classroommanager;
  import android.support.v7.app.AppCompatActivity;
  import android.os.Bundle;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
  import android.widget.EditText;
  import android.widget.Toast;

  import java.util.ArrayList;

  import static co.tekitall.classroommanager.R.id.NumOfStudents;

  public class Classroom extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_classroom);
      Button button = (Button) findViewById(R.id.SubmitClassRoomInfoButton);

    }

    void ClassroomElements() {
      //ArrayList
      ArrayList<EditText> arrayList = new ArrayList<>();
      arrayList.add((EditText) findViewById(R.id.Teacher_Name));
      arrayList.add((EditText) findViewById(R.id.Room_Number));
      arrayList.add((EditText) findViewById(R.id.ClassroomHelper));
      arrayList.add((EditText) findViewById(R.id.NumOfStudents));
    }

    OnClickListener listener = new OnClickListener() {
      @Override
      public void onClick(View v) {
        EditText numofstudents = (EditText) findViewById(R.id.NumOfStudents);
        String getstucount = numofstudents.getText().toString();

        int setstucount = Integer.parseInt(getstucount);

        if(setstucount < 0) {

          numofstudents.setText("");
          Toast toast = Toast.makeText(Classroom.this, "Please try Again! Number must be greater then 0 and less than 100...", Toast.LENGTH_LONG);
          toast.show();

        }

        if(setstucount > 100) {

          numofstudents.setText("");
          Toast toast = Toast.makeText(Classroom.this, "Please try Again! Number must be greater then 0 and less than 100...", Toast.LENGTH_LONG);
          toast.show();

        } else
          numofstudents.setText("");
          Toast toast = Toast.makeText(Classroom.this, "Good Job", 
          Toast.LENGTH_LONG);
          toast.show();
        }
    };
  }

2 个答案:

答案 0 :(得分:3)

您需要使用

绑定button和侦听器
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_classroom);
    Button button = (Button) findViewById(R.id.SubmitClassRoomInfoButton);
    button.setOnClickListener(listener);
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

另外使用ifelse-if代替多个if,因为一个数字只能小于0,否则大于100或者等于0或100

if(setstucount < 0){//...code}
else if(setstucount > 100){//...code}
else  {//...code}

答案 1 :(得分:0)

看起来你有一个Button和一个OnClickListener,但你永远不会将它们连接在一起。例如:

button.setOnClickListener(listener);