2016-07-12 30 views
-1

我有一個editText,我設置setOnFocusChangeListener來打開微調框。 一旦我從微調框中選擇一個項目,我希望所選項目顯示在相同的編輯文本上。如何設置微調選框項目editTextFocusChange上編輯文本 - Android

下面是我試過的代碼。

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

可能的重複[如何在Android中使用onItemSelected?](http://stackoverflow.com/questions/20151414/how-can-i-use-onitemselected-in-android) –

回答

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中的微調器上使用OnItemSelectedListener。 Red more from Android Developers。祝你好運..

+0

謝謝代碼非常多。但是我認爲你可以在選擇完成後設置Spinner的可見性來隱藏它,並且它會反映在edittext上。 – ASN

+1

你可以使用「spinner.setVisibility(View.GONE)」隱藏它;「您可以在if(hasFocus)的其他部分使用它。spinner.setVisibility(View.VISIBLE); } else {spinner.setVisibility(View.GONE);} –

相關問題