如何在editTextFocusChange- Android上设置微调器选定项目以编辑文本

时间:2016-07-12 03:22:50

标签: android

我有一个editText,我设置setOnFocusChangeListener来打开一个微调器。 一旦我从微调器中选择一个项目,我希望所选项目显示在同一编辑文本上。

以下是我尝试的代码。

List<String> tal = new ArrayList<String>();
        tal.add("1");
        tal.add("2");
        tal.add("3");
        tal.add("4");
        tal.add("5");

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, tal);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

                @Override
                public void onFocusChange(View arg0, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    if(hasFocus){
                        spinner.performClick();

                    }
                }
            });
            editText.setText(spinner.getSelectedItem().toString()); //this is taking the first value of the spinner by default. 

XML:

<EditText
        android:hint="Select A Value"
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_edittext"
        android:layout_weight="0.05"
        android:singleLine="true"/>

<Spinner android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner" />

1 个答案:

答案 0 :(得分:4)

您可以使用这样的代码。我为你做了..

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                spinner.setVisibility(View.VISIBLE);

            }
        }
    });

    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            editText.setText(spinner.getSelectedItem().toString()); //this is taking the first value of the spinner by default.

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub

        }
    });

你只能在android。Red more from Android Developers的spinner上使用OnItemSelectedListener。祝你好运..