简体   繁体   English

根据Android中的用户输入更改EditText和Spinner的值

[英]Change the values of EditText and Spinner based on User Input in Android

I have an editText and a Spinner in my android xml file. 我的android xml文件中有一个editText和一个Spinner。 I want to change the values of the EditText and Spinner based on the user input. 我想根据用户输入更改EditText和Spinner的值。 For example, if the user enters 7,14,21,28 in the EditText and chooses Days in the Spinner, I want the values to automatically change to 1,2,3,4 Weeks respectively. 例如,如果用户在EditText中输入7,14,21,28并在Spinner中选择Days,我希望这些值分别自动更改为1,2,3,4周。 The same applies for as possible combinations. 同样适用于可能的组合。

  1. 24 hours - 1 Day 24小时-1天
  2. 7,14,21,28 Days - 1,2,3,4 Weeks 7,14,21,28天-1,2,3,4周
  3. 4,8,12,16,20,24,28 weeks - 1,2,3,4,5,6,7 Months 4,8,12,16,20,24,28星期-1,2,3,4,5,6,7个月

Please find below the code snippets for the EditText and the spinner. 请在下面找到EditText和微调框的代码段。

EditText: EditText上:

<android.support.design.widget.TextInputEditText
                android:id="@+id/frequencyDaysEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/frequencyTime"
                android:inputType="number" />

Spinner: 微调:

<Spinner
            android:id="@+id/frequencySpinner"
            android:layout_width="0dp"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:layout_weight="0.2"
            android:entries="@array/frequencyArray" />

The Frequency array has values: {Hours, Days,Weeks and months}. “频率”数组的值是:{小时,天,周和月}。

Note: I have restricted the range of EditText from 1-30. 注意:我已限制EditText的范围为1-30。 Also, I want this to happen when the user finishes choosing the value and not wait until the user clicks on the submit button. 另外,我希望在用户完成选择值时才发生这种情况,而不是等到用户单击“提交”按钮时才会发生这种情况。

I want to write a validation function in Java which is going to do the function as described above. 我想用Java编写一个验证函数,它将如上所述执行该函数。 Please provide any help with answers. 请提供任何答案帮助。

EditText edittext = (EditText) findViewById(R.id.frequencyDaysEditText);
Spinner spinner = (Spinner) findViewById(R.id.frequencySpinner);

edittext.addTextChangedListener(new TextWatcher() {

    @Override
    public void afterTextChanged(Editable s) {}

    @Override    
    public void beforeTextChanged(CharSequence s, int start,
      int count, int after) {
    }

    @Override    
    public void onTextChanged(CharSequence s, int start,
      int before, int count) {

        if(s.length() != 0)
        {
            String name= null;
            if(spinner != null && spinner .getSelectedItem() !=null
            {
                name = (String)spinner.getSelectedItem();

                  //Do what you want to do here

            } else  { 

            }
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM