How to add floating label on Spinner

前端 未结 10 1731
Happy的楠姐
Happy的楠姐 2020-12-12 14:46

After using the Android Design Support Library\'s TextInputLayout to place a floating label above an EditText component, I was wondering if there is a way to add a floating

10条回答
  •  星月不相逢
    2020-12-12 15:33

    Here is my trick,

    the good things is that everything will work like you want,

    but the bad is that it is increasing layout hierarchy, and you have to handle functionality in code, and it is an ugly solution:

        
    
            
    
                
    
            
    
            
    
        
    

    and override adapter for spinner, to make selected values transparent

    public class MySpinnerAdapter extends SimpleAdapter {
        Context mContext;
    
        public MySpinnerAdapter(Context context, List data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
            mContext = context;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = super.getView(position, convertView, parent);
    
            TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
                tv.setTextColor(ContextCompat.getColor(mContext, R.color.transparent));
            return convertView;
        }
    }
    

    and after selecting in spinner, just get selected text and set it to EditText and it will have the same effect with animation

    yourSpinnerView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView adapterView, View view, int i, long l) {
                //get your selected text from adapter or from where you want 
                String selectedText = adapterView.getItemAtPosition(i));
    
                if (i != 0) { 
                    edt.setText(selectedText);
                } else { 
                    // if in case your spinner have first empty text, 
                    // then when spinner selected, just empty EditText.
                    edt.setText("");
                }
            }
    
            @Override
            public void onNothingSelected(AdapterView adapterView) {
    
            }
        });
    

    if you have any question Ask me

提交回复
热议问题