Как получить переменную edittext: java android? - PullRequest
0 голосов
/ 01 апреля 2020

Я хочу получить разные переменные для editText, который я кодировал с java (L OOP), а не XML.

Я работаю над проектом, в котором пользователя спрашивают, сколько курсов было Вы предлагаете ?, если 10 EditText появится 10 раз. Но я хочу получить имя переменной каждого editText и его значение. Я получаю только значение последнего.

public class CourseEnter extends AppCompatActivity {

private TextInputLayout noOfCourse, textInputLayout,

courseCreditLoadInputLayout, courseScoreInputLayout;

private TextInputLayout dropDown;
private int i;
private ProgressDialog dialog;
private LinearLayout linearLayout;

private TextInputEditText courseCode, courseTitle, courseCreditLoad, courseScore;
String[] update;

ArrayList<String> courseTitles= new ArrayList<String>();//not used for now
ArrayList<String> courseCodes= new ArrayList<String>();//not used for now
ArrayList<String> courseLoads= new ArrayList<String>();//not used for now
ArrayList<String> courseScores= new ArrayList<String>();//not used for now

String courseTitleId;
private Button buttonNext;
private Button button;
private TextInputLayout courseCodeInputLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course_enter);
    String[] SEMESTERS = new String[]{"First Semester", "Second Semester"};
    String[]   LEVELS = new String[] {"100 Level", "200 Level", "300 Level", "400 Level","500 Level", "600 Level"
            ,"700 Level"};
    dropDown = findViewById(R.id.dropdownM);
    courser = findViewById(R.id.coureser);

    ArrayAdapter<String> adapter=new ArrayAdapter<>(getApplicationContext(),R.layout.item_list,LEVELS);
    AutoCompleteTextView editTextFilledExposedDropdown =
            findViewById(R.id.autoCompleteViewForLevel);
    editTextFilledExposedDropdown.setAdapter(adapter);
    ArrayAdapter<String> adapterSemester = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, SEMESTERS);
    AutoCompleteTextView editSEMESTER =
            findViewById(R.id.semester2);
    editSEMESTER.setAdapter(adapterSemester);
    buttonNext = findViewById(R.id.secondButton);


    buttonNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            courseColumn();

        }
    });

}

void courseColumn() {
    noOfCourse = findViewById(R.id.numberOfCourses);
    if (!TextUtils.isEmpty(noOfCourse.getEditText().getText().toString())) {
        String generateCourse = noOfCourse.getEditText().getText().toString();
        int courseToInt = Integer.parseInt(generateCourse);


        linearLayout = findViewById(R.id.linearLayout);


        for (i = 1; i <= courseToInt; i++) {
            textInputLayout = new TextInputLayout(this);
            courseTitle = new TextInputEditText(this);
            textInputLayout.setHelperText("Enter Course Title for Course " + i + ":");
            textInputLayout.setHelperTextEnabled(true);
            courseTitle.setId(i);
            textInputLayout.setHintTextColor(android.content.res.ColorStateList.valueOf(Color.RED));
            //courseTitle.setHintTextColor(Color.RED);
            courseTitle.setTextColor(Color.RED);

            String a = Integer.toString(i);
            courseTitleId = "courseTitle" + a;
            // update[i]=courseTitleId;

            //For Course Code

            courseCodeInputLayout = new TextInputLayout(this);
            courseCode = new TextInputEditText(this);
            courseCodeInputLayout.setHelperText("Enter Course Code for Course " + i + ":");
            courseCodeInputLayout.setHelperTextEnabled(true);
            courseCode.setAllCaps(true);

            // lastly added
            courseCode.setId(i);


            //for Course Credit Load
            courseCreditLoadInputLayout = new TextInputLayout(this);
            courseCreditLoad = new TextInputEditText(this);
            courseCreditLoadInputLayout.setHelperText("Enter Course Credit 
            or Unit for Course " + i + " only numbers" + ":");

            courseCreditLoadInputLayout.setHelperTextEnabled(true);

            courseCreditLoad.setAllCaps(true);
            courseCreditLoad.setInputType(InputType.TYPE_CLASS_NUMBER);
            courseCreditLoadInputLayout.setCounterEnabled(true);
            courseCreditLoadInputLayout.setCounterMaxLength(1);

            //for Score
            courseScoreInputLayout = new TextInputLayout(this);
            courseScore = new TextInputEditText(this);
            courseScoreInputLayout.setHelperText("Enter Score for Course " 
            + i + " only numbers" + ":");
            courseScoreInputLayout.setHelperTextEnabled(true);
            courseScore.setAllCaps(true);
            courseScore.setInputType(InputType.TYPE_CLASS_NUMBER);
            courseScoreInputLayout.setCounterEnabled(true);
            courseScoreInputLayout.setCounterMaxLength(3);

            Button btn = new Button(this);
            for (int bt = 1; bt <= i; bt++) {
                btn.setText("STEP " + bt);
                btn.setVisibility(View.VISIBLE);
                btn.setTextColor(Color.RED);
                btn.setBackgroundColor(Color.YELLOW);
            }
            //toString methods of all the inputs
           String courseT= courseTitle.getText().toString();
            String courseC= courseCode.getText().toString();
            String courseL= courseCreditLoad.getText().toString();
            String courseS= courseScore.getText().toString();
            courseTitle.setLayoutParams(new 

         LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
           LinearLayout.LayoutParams.WRAP_CONTENT));
            linearLayout.addView(btn);

            linearLayout.addView(textInputLayout);
            linearLayout.addView(courseTitle);
            linearLayout.addView(courseCodeInputLayout);
            linearLayout.addView(courseCode);
            linearLayout.addView(courseCreditLoadInputLayout);
            linearLayout.addView(courseCreditLoad);
            linearLayout.addView(courseScoreInputLayout);
            linearLayout.addView(courseScore);


            //remeber to change the button id and name=
            button = new Button(this);
            button.setVisibility(View.VISIBLE);
            button.setEnabled(true);
            button.setBackgroundColor(Color.MAGENTA);
            button.setText("Proceed");
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog = new ProgressDialog(CourseEnter.this);
                    dialog.setTitle("GUIDE FROM VICTORHEZ!!!");
                    dialog.setMessage("For you to save your result, you 
  must fill all fields provided above");
                   dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                   dialog.setCancelable(false);
                   dialog.setButton(DialogInterface.BUTTON_NEGATIVE, 
     "OKAY", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialoga, int 
     which) {
                           dialog.dismiss();
                           proceedMethod();
                       }
                   });
                    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "GO 
       BACK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialoga, int 
           which) {
                            dialog.dismiss();
                        }
                    });
                   dialog.show();



                }
            });

        }
        linearLayout.addView(button);
    } else {
        Toast.makeText(this, "Enter Field: ", Toast.LENGTH_LONG).show();
        noOfCourse.setError("ENTER FIELD");

    }

  }

  private void proceedMethod() {

  if (TextUtils.isEmpty(courseTitle.getText()))
 {
   textInputLayout.setError("Error: Enter Field");
   }
  else if(TextUtils.isEmpty(courseCode.getText()))
 {
 courseCodeInputLayout.setError("Error: Enter Field");
 }
else if(TextUtils.isEmpty(courseCreditLoad.getText()))
{
courseCreditLoadInputLayout.setError("Error: Enter Field");
}
else if(TextUtils.isEmpty(courseScore.getText()))
{
courseScoreInputLayout.setError("Error: Enter Field");
}
else
{
Toast.makeText(CourseEnter.this,"VICTORHEZ",Toast.LENGTH_LONG).show();
}
}


}

Ответы [ 2 ]

0 голосов
/ 01 апреля 2020

Создайте динамически EditText в TableLayout, затем получите доступ к нему по его строке.

0 голосов
/ 01 апреля 2020

Либо вы храните его в массиве, карте или setTag. Вы только что создали элементы, но не можете получить к ним доступ снова. Это зависит от того, как вы планируете использовать элементы. Если вы можете добавить больше деталей к вопросу, то, возможно, мы сможем установить лучший ответ.

...