如何创建第二个微调器,其选项列表取决于第一个微调器的输入?

时间:2019-03-19 14:13:46

标签: java android android-spinner

我已经在网上搜索了,找不到解决方案。

我要执行的操作是在第二个微调器中显示数组的列表,具体取决于第一个微调器中的选定选项。

逻辑将是这样的: 如果第一个微调器= CSE / IT

然后,第二个微调选项将是: 1. BCA 2. MCA

这是我的Java代码:

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener
{
private EditText TextFname;
private EditText TextMname;
private EditText TextLname;
//private EditText TextDept;
private Spinner SpinDept;
private Spinner SpinProg;
//private EditText TextProg;
private EditText TextSemester;
private EditText TextRolln;
private EditText TextEmail;
private EditText TextPassword;
private EditText TextPasswordConfirm;

//private FirebaseFirestore db = FirebaseFirestore.getInstance();
// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();
private ProgressBar pBar;
private View bgBlur;

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

    TextFname = findViewById(R.id.Fname);
    TextMname = findViewById(R.id.Mname);
    TextLname = findViewById(R.id.Lname);
    //TextDept = findViewById(R.id.Dept);

    SpinDept = findViewById(R.id.Dept);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.department_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    SpinProg = findViewById(R.id.Prog);
    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
            R.array.programme_array, android.R.layout.simple_spinner_item);
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    //TextProg = findViewById(R.id.Prog);
    TextSemester = findViewById(R.id.Semester);
    TextRolln = findViewById(R.id.Rolln);
    TextEmail = findViewById(R.id.Email);
    TextPassword = findViewById(R.id.Password);
    TextPasswordConfirm = findViewById(R.id.PasswordConfirm);

    findViewById(R.id.SubmitButton).setOnClickListener(this);
    pBar=findViewById(R.id.indeterminateBar);
    bgBlur=findViewById(R.id.bgblur);
}

//Validation method
private boolean validate()
{
    AwesomeValidation mAwesomeValidation = new AwesomeValidation(BASIC);
    mAwesomeValidation.addValidation(TextFname, "\\D+", "Invalid First Name");
    mAwesomeValidation.addValidation(TextLname, "\\D+", "Invalid Last Name");
    //mAwesomeValidation.addValidation(TextDept, "\\D+", "Invalid Department Name");
    //mAwesomeValidation.addValidation(TextProg, "\\D+", "Invalid Programme Name");
    mAwesomeValidation.addValidation(TextSemester, "[1-9]+[0-9]{0,}", "Invalid Semester (Cannot be less than 0)");
    mAwesomeValidation.addValidation(TextRolln, "[a-zA-Z-0-9\\s]+", "Invalid Roll Number");
    mAwesomeValidation.addValidation(TextEmail, Patterns.EMAIL_ADDRESS, "Invalid Email Address");
    String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d])(?=.*[~`!@#\\$%\\^&\\*\\(\\)\\-_\\+=\\{\\}\\[\\]\\|\\;:\"<>,./\\?]).{6,}";
    mAwesomeValidation.addValidation(TextPassword, regexPassword, "Use 6 or more characters with a mix of upper & lower letters, numbers & symbols");
    mAwesomeValidation.addValidation(TextPasswordConfirm, TextPassword, "Password does not match");
    return mAwesomeValidation.validate();
}
@Override
public void onClick(View v)
{
    // Check for particular button click, because this method will be called for every
    // click on any view on which onClickListener is set as setOnClickListener(this).
    // In this case currently it doesn't matter as there is only one button, but in case
    // if you also add for example clear field button, then you need to know which
    // button was clicked.

    switch (v.getId())
    {
        case R.id.SubmitButton:
        if (validate())
        {
            String TextDept = SpinDept.getSelectedItem().toString();
            String TextProg = SpinProg.getSelectedItem().toString();


            pBar.setVisibility(View.VISIBLE);
            bgBlur.setVisibility(View.VISIBLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            //Toast.makeText(this, "Validation successful", Toast.LENGTH_SHORT).show();

            /*String Firstname = getTrimmedInput(TextFname);
            String Middlename = getTrimmedInput(TextMname);
            String Lastname = getTrimmedInput(TextLname);
            String Department = getTrimmedInput(TextDept);
            String Programme = getTrimmedInput(TextProg);
            String Semester = getTrimmedInput(TextSemester);
            String Rollnumber = getTrimmedInput(TextRolln);
            String Password = getTrimmedInput(TextPassword);*/
            String Email = getTrimmedInput(TextEmail);
            final CollectionReference dbUsers = db.collection("Students");
            final DocumentReference dbDocs = dbUsers.document(Email);
            //Student student = new Student(Firstname, Middlename, Lastname, Department, Programme, Integer.parseInt(Semester), Rollnumber, Email, Password);



            //Alternative way how to create data model. I think builder pattern is easier
            // to operate as you don't have to know in which order you should pass variables
            // (especially when you have a lot of them) to model constructor.
            // Although I don't know if my class would work as I don't know how your
            // DB backend requests data from your student class as in my model some
            // getter method name cases are different. Currently I created my Student
            // model as example and it's not used.
            final StudentImproved studentImproved =  new StudentImproved.Builder()
                .setFirstName(getTrimmedInput(TextFname))
                .setMiddleName(getTrimmedInput(TextMname))
                .setLastName(getTrimmedInput(TextLname))
                .setDepartment(TextDept)
                .setProgramme(TextProg)
                .setSemester(Integer.parseInt(getTrimmedInput(TextSemester)))
                .setRollNumber(getTrimmedInput(TextRolln))
                .setEmail(getTrimmedInput(TextEmail))
                .setPassword(getTrimmedInput(TextPassword))
                //.setPasswordConfirm(getTrimmedInput(TextPasswordConfirm))
                .build();

            dbUsers.document(Email)
                    .get()
                    .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>()
                    {
                        @Override
                        public void onComplete(@NonNull Task<DocumentSnapshot> task)
                        {
                            if (task.isSuccessful())
                            {
                                if (task.getResult().exists())
                                {
                                    pBar.setVisibility(View.GONE);
                                    bgBlur.setVisibility(View.GONE);
                                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                                    Toast.makeText(RegisterActivity.this, "You already have your data stored in the database", Toast.LENGTH_LONG).show();
                                }
                                else
                                    {
                                        dbDocs.set(studentImproved)

                                                .addOnSuccessListener(new OnSuccessListener<Void>()
                                                {
                                                    @Override
                                                    public void onSuccess(Void aVoid)
                                                    {
                                                        pBar.setVisibility(View.GONE);
                                                        bgBlur.setVisibility(View.GONE);
                                                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                                                        Toast.makeText(RegisterActivity.this, "Successfully Registered",Toast.LENGTH_LONG).show();
                                                    }
                                                })
                                                .addOnFailureListener(new OnFailureListener()
                                                {
                                                    @Override
                                                    public void onFailure(@NonNull Exception e)
                                                    {
                                                        pBar.setVisibility(View.GONE);
                                                        bgBlur.setVisibility(View.GONE);
                                                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                                                        Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                                                    }
                                                });
                                    }
                            }
                        }
                    });



        }
        /*else
            {
                Toast.makeText(this, "Validation failed", Toast.LENGTH_LONG).show();
            }
            break;*/
    }
}

private String getTrimmedInput(EditText text)
{
    return text.getText().toString().trim();
}
}

这是我的Spinner XML代码:

        <Spinner
            android:id="@+id/Dept"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="131dp"
            android:layout_marginTop="24dp"
            android:layout_marginEnd="132dp"
            android:entries="@array/department_array"
            android:spinnerMode="dropdown"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/Rolln" />

        <Spinner
            android:id="@+id/Prog"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="179dp"
            android:layout_marginTop="24dp"
            android:layout_marginEnd="180dp"
            android:entries="@array/programme_array"
            android:spinnerMode="dropdown"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/Dept" />

这是我的String XML代码:

    <string-array name="department_array">
    <item>Civil</item>
    <item>CSE/IT</item>
    <item>Electronics</item>
</string-array>
<string-array name="programme_array">
    <item>B.Tech Civil</item>
    <item>BCA</item>
    <item>MCA</item>
</string-array>

2 个答案:

答案 0 :(得分:0)

spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            // load spinner2 data from database method loadData
            List<String> spinner2Data= helper.loadData(spinner1.getSelectedItem().toString());

            // Create adapter for spinner
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(CurrentActivity.this,android.R.layout.simple_spinner_dropdown_item,android.R.id.text1,spinner2Data);

            // Drop down layout style - list view with radio button
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            // attaching data adapter to spinner
            spinner2.setAdapter(dataAdapter);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

答案 1 :(得分:0)

在第一个微调器的setOnItemSelectedListener中,根据ID匹配或部门名称加载第二个微调器。当您询问将setOnItemSelectedListener放在哪里时,它应该是您活动的第一种方法onCreate中。为此,您可以使用模型类。

SpinProg = findViewById(R.id.Prog);

    SpinDept.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
                        programmeArray.clear();
                        // Here put your logic for selecting programs against each department and initialize programmeArray then load progSpinner with that array
                         /*
               *  for(int i=0; i<totalPrograms.size; i++){
               *
               *  
          *if(totalPrograms.get(i).getName.equals(totalDepartments.get(position).getName)){
               *  programmeArray.add(totalPrograms.get(i));
                *  }
               *  }
               * */

    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
            programmeArray, android.R.layout.simple_spinner_item);
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) { }
            });