2015-12-10 3 views
1

Я хотел бы изменить цвет текста Spinner, выпадающего на черный.Как изменить цвет текста выпадающих элементов Spinner?

У меня есть собственный счетчик, в котором перечислены разные языки. Он имеет ImageView и TextView. Spinner показан на синем фоне с белым текстом, и он выглядит отлично.

Проблема заключается в том, что при нажатии на нее появляется выпадающее меню, но текст едва заметен из-за светло-серого цвета выпадающего списка и белого цвета текста.

Это код Spinner в activity_main.xml:

<Spinner 
    android:id="@+id/languageSpinner" 
    style="@android:style/Widget.Material.Light.DropDownItem.Spinner" 
    android:layout_width="140dp" 
    android:layout_height="40dp" 
    android:prompt="@string/selectLanguageSpinner" 
    android:spinnerMode="dropdown" /> 

Это spinner_row_layout.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="8dp" 
     android:orientation="horizontal"> 

     <ImageView 
      android:id="@+id/icon" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center_vertical" /> 

     <TextView 
      android:id="@+id/language" 
      android:layout_width="wrap_content" 
      android:layout_height="40dp" 
      android:layout_gravity="center_vertical" 
      android:layout_marginEnd="10dp" 
      android:layout_marginStart="5dp" 
      android:gravity="center_vertical" 
      android:lineSpacingExtra="20dp" 
      android:minHeight="40dp" 
      android:textColor="@color/white" 
      android:textSize="20sp" /> 
    </LinearLayout> 
</LinearLayout> 

Здесь цвет текста выбран белый, потому что мне это нужно, чтобы быть белым когда ничего не выбрано.

Это код в styles.xml:

<!-- Base application theme. --> 
    <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar"> 
     <!-- Customize your theme here. --> 
     <item name="colorPrimary">@color/myAppPrimaryColor</item> 
     <item name="colorPrimaryDark">@color/myAppPrimaryDarkColor</item> 
     <item name="colorAccent">@color/myAppAccentColor</item> 
     <item name="android:dropDownListViewStyle">@style/TestSpinnerStyle</item> 
     <item name="android:spinnerItemStyle">@style/mySpinnerItemStyle</item> 
    </style> 

    <style name="mySpinnerItemStyle"> 
     <item name="android:paddingLeft">5dp</item> 
     <item name="android:paddingBottom">3dp</item> 
     <item name="android:textSize">20sp</item> 
     <item name="android:textColor">@color/white</item> 
    </style> 

    <!-- ^^ Here I need to set the color to white, because I also have default 
      spinner on the activity that needs to have a default white color. 
      But when the default spinner is clicked, the color of the 
      drop down items is black. How can I do that with my custom spinner? --> 

    <style name="TestSpinnerStyle" parent="android:style/Widget.ListView.DropDown"> 
     <item name="android:textSize">22sp</item> 
     <item name="android:textColor">@color/black</item> 
     <item name="android:height">20dp</item> 
     <item name="android:divider">@color/gray</item> 
     <item name="android:dividerHeight">1dp</item> 
     <item name="android:dividerPadding">5dp</item> 
     <item name="android:background">@color/default_gray</item> 
    </style> 

    <!-- ^^ The text color property here is not reflected.. --> 

Кто-нибудь есть какие-либо предложения, как сделать это?

EDIT: После помощи комментариев и ответов мне удалось это сделать. Я думал, что это можно сделать в XML ... В любом случае в коде Java, это то, что я сделал:

Когда пользовательский адаптер определен, нам необходимо переопределить метод getDropDownView, который запускается, когда счетчик щелчок и выпадение появляется. Метод getView также должен быть переопределен, поэтому мы можем обрабатывать цвет по умолчанию, если не нажата кнопка Spinner. Другими словами, вот код:

public class CustomSpinnerAdapter extends ArrayAdapter<String> { 
     public CustomSpinnerAdapter(Context context, int textViewResourceId, String[] objects, TypedArray image){ 
      super(context, textViewResourceId, objects); 
     } 

     @Override 
     public View getDropDownView(int position, View convertView, ViewGroup parent){ 
      LayoutInflater inflater = getLayoutInflater(); 
      View row = inflater.inflate(R.layout.spinner_row_layout, parent, false); 

      TextView label = (TextView) row.findViewById(R.id.language); 
      label.setText(languages_list[position]); 

      label.setTextColor(getResources().getColor(android.R.color.black)); 

      ImageView icon = (ImageView) row.findViewById(R.id.icon); 
      icon.setImageDrawable(icons_list.getDrawable(position)); 

      return row; 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent){ 
      LayoutInflater inflater = getLayoutInflater(); 
      View row = inflater.inflate(R.layout.spinner_row_layout, parent, false); 

      TextView textView = (TextView) row.findViewById(R.id.language); 
      textView.setText(languages_list[position]); 
      textView.setTextColor(getResources().getColor(android.R.color.white)); 

      ImageView icon = (ImageView) row.findViewById(R.id.icon); 
      icon.setImageDrawable(icons_list.getDrawable(position)); 

      return row; 
     } 
    } 

Обратите внимание, что цвет TextView в getDropDownView установлен в черный, в то время как в getView он установлен на белый.

+0

Вы используете собственную реализацию адаптера для показа Spinner элементов? – flyingAssistant

+0

@flyingAssistant Я сделал это как в этом уроке: http://www.edureka.co/blog/custom-spinner-in-android/ – Apostrofix

ответ

4

Я сделал эту вещь, как это, но в BaseAdapter

public View getDropDownView(int position, View convertView, ViewGroup parent) { 
      View view = convertView; 
      if (view == null) { 
       view = inflater.inflate(R.layout.spinner_item, null); 
      } 

      TextView txtTestText = (TextView) view.findViewById(R.id.txtSpinnerRowText); 
      txtTestText.setText(list.get(position).getText()); 
      if (getSelectedPosition() == position) { 
       txtTestText.setTextColor(context.getResources().getColor(android.R.color.holo_blue_dark)); 
      } else { 
       txtTestText.setTextColor(context.getResources().getColor(android.R.color.primary_text_light)); 
      } 
      return view; 
     } 
+0

Что такое 'getSelectedPosition()'? – Apostrofix

+0

Это индекс выбранного элемента строки 'Spinner', определенного в поле« BaseAdapter »как поле. Я меняю этот индекс всякий раз, когда выпадающий элемент «Spinner» выбирается ('OnItemSelectedListener.onItemSelected') или не выбран (' OnItemSelectedListener.onNothingSelected'). – flyingAssistant

+0

Спасибо, мне удалось это сделать. Я отредактирую свой вопрос с полным решением. Я смог изменить цвет в 'getDropDownView' и' getView', так что теперь он выглядит отлично. – Apostrofix

0

попробуйте это, я надеюсь, что это не работает.

((Spinner)findViewById(R.id.spinnergender)).setAdapter(adapter); 
     ((Spinner)findViewById(R.id.spinnergender)).setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
      @Override 
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
       Log.e("Value",""+position); 
       ((TextView) ((Spinner)findViewById(R.id.spinnergender)).getSelectedView()).setTextColor(getResources().getColor(R.color.cyan)); 
       if(parent.getItemAtPosition(position).toString().equals(getResources().getString(R.string.Gender))) { 
        ((TextView) ((Spinner)findViewById(R.id.spinnergender)).getSelectedView()).setTextColor(getResources().getColor(R.color.Text)); 
       } 

      } 
0

Вы должны создать собственный адаптер (который расширяет BaseAdapter) для блесны и на getDropDownView раздувать пользовательские spinner_item_dropdown.xml, который устанавливается с вашими пожеланиями.

Смежные вопросы