2015-03-30 5 views
2

У меня есть AutoCompleteTextView, к которому я хотел бы применить некоторый стиль. Код функционально работает, и базовый стиль отлично, но есть некоторые более продвинутые вещи, которые я хотел бы изменить. В частности:Styling Android AutoComplete

Пользовательские Гарнитуры

Моей панели поиск использует пользовательский шрифт моего приложения, но строки предсказания отображается с использованием шрифта шрифта по умолчанию в системе. Вот как я установить шрифт для результата поиска:

mSearchTextView.setTypeface(font.mAvenirLTStandardLight); 

Удалить тень от выпадающего списка

Значения по умолчанию опции выпадающей есть тень, и мое приложение использует более плоский дизайн. Я хотел бы удалить это, если это возможно.

Добавить радиус в выпадающий

я смог обогнуть радиус каждой строки результата, но я был не в состоянии понять, как применить кривой для всего выпадающего списка.

Вот мои применимые код разделы:

private void setAutoCompleteListener() { 
    AutoCompleteAdapter adapter = new AutoCompleteAdapter(mContext, 
      R.layout.autocomplete_list_item, mLatLng); 

    mSearchTextView.setAdapter(adapter); 

    mSearchTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 
      String str = (String) adapterView.getItemAtPosition(i); 
      initiateSearch(); 
      hideKeyboard(); 
     } 
    }); 
} 

activity_map.xml

<AutoCompleteTextView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/actvSearch" 
    android:hint="@string/search_or_enter_address" 
    android:background="@color/transparent_white" 
    android:textSize="14sp" 
    android:textColor="@color/black" 
    android:layout_centerVertical="true" 
    android:layout_toEndOf="@id/ibLogoImage" 
    android:layout_toStartOf="@id/ibSearch" 
    android:dropDownAnchor="@id/search_bar" 
    android:dropDownVerticalOffset="0dp" /> 

autocomplete_list_item.xml

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@color/white" 
    android:textColor="@color/black" 
    android:paddingTop="10dp" 
    android:paddingBottom="10dp" 
    android:paddingStart="25dp" 
    android:paddingEnd="25dp"/> 

AutoCompleteAdapter.java

public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable { 
    private static String TAG = "AutoComplete"; 

    /* 
    * The lat/lng of the current location. 
    */ 
    private LatLng mLatLng; 

    /* 
    * A list of the autocomplete results. 
    */ 
    private ArrayList<String> mResults; 

    public AutoCompleteAdapter(Context context, int textViewResourceId, LatLng latLng) { 
     super(context, textViewResourceId); 
     Log.d(TAG, "Center of Screen: " + latLng.toString()); 
     mLatLng = latLng; 
    } 

    @Override 
    public int getCount() { 
     return mResults.size(); 
    } 

    @Override 
    public String getItem(int index) { 
     return mResults.get(index); 
    } 

    @Override 
    public Filter getFilter() { 
     Filter filter = new Filter() { 
      @Override 
      protected FilterResults performFiltering(CharSequence constraint) { 
       FilterResults filterResults = new FilterResults(); 
       if (constraint != null) { 
        // Retrieve the AutocompleteHelper results. 

        mResults = AutoCompleteHelper.getAutoCompletePredictions(
          constraint.toString(), 
          mLatLng); 

        // Assign the data to the FilterResults 
        filterResults.values = mResults; 
        filterResults.count = mResults.size(); 
       } 
       return filterResults; 
      } 

      @Override 
      protected void publishResults(CharSequence constraint, FilterResults results) { 
       if (results != null && results.count > 0) { 
        notifyDataSetChanged(); 
       } 
       else { 
        notifyDataSetInvalidated(); 
       } 
      }}; 
     return filter; 
    } 
} 
+0

Я пытаюсь удалить выпадающее меню тени, а также, вам удалось найти решение для этого? –

+0

Yup - просто добавил его в раздел «Ответ». Дайте мне знать, можно ли улучшить какой-либо раздел :) –

ответ

3

Я смог понять все на самом деле :) Вот соответствующий код, который я использовал.

Пользовательские Гарнитуры

Хитрость этого является то, что я должен был установить свой шрифт как mAutoCompleteTextView и tvAutocompleteListItem в моей деятельности.

Удалить Тень

я установить фон mAutoCompleteTextView быть R.drawable.autocomplete_dropdown. В этом Drawable важная линия

<stroke 
    android:width="0dip" 
    android:color="@color/cp_green" /> 

Радиус

Радиус был установлен в R.drawable.autocomplete_dropdown так:

<corners 
     android:radius="20dip"/> 

MapActivity.java

private void setAutoCompleteListener() { 
    mAutoCompleteTextView.setDropDownBackgroundDrawable(
      mContext.getResources().getDrawable(R.drawable.autocomplete_dropdown)); 


    mAutoCompleteTextView.setAdapter(
      new AutoCompleteAdapter(mContext, R.layout.autocomplete_list_item, mLatLng)); 

    mAutoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 
      String autoCompleteText = (String) adapterView.getItemAtPosition(i); 
      mAutoCompleteTextView.setText(autoCompleteText); 
      initiateSearch(); 
      hideKeyboard(); 
     } 
    }); 

    mAutoCompleteTextView.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { 

     } 

     @Override 
     public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { 

     } 

     @Override 
     public void afterTextChanged(Editable editable) { 
      if (editable.length() > 0) { 
       mClearTextIcon.setVisibility(View.VISIBLE); 
      } else { 
       mClearTextIcon.setVisibility(View.INVISIBLE); 
      } 
     } 
    }); 
} 


public void applyFonts() { 
    Log.d(TAG, "Applying Fonts."); 

    FontHelper.applyFont(findViewById(R.id.rlMap), mContext); 
    font = Font.getInstance(getApplicationContext()); 

    mAutoCompleteTextView.setTypeface(font.mAvenirLTStandardLight); 

    LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View view = inflater.inflate(R.layout.autocomplete_list_item, null); 

    TextView tvAutocompleteListItem = (TextView) view.findViewById(R.id.tvAutocompleteListItem); 
    tvAutocompleteListItem.setTypeface(font.mAvenirLTStandardLight); 
} 

autocomplete_dropdown.XML

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid 
     android:color="@color/white" /> 

    <stroke 
     android:width="0dip" 
     android:color="@color/cp_green" /> 

    <corners 
     android:radius="20dip"/> 

    <padding 
     android:left="25dip" 
     android:top="10dip" 
     android:right="25dip" 
     android:bottom="10dip" /> 
</shape> 

autocomplete_list_item.xml

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@color/white" 
    android:textColor="@color/gray_text" 
    android:textSize="14sp" 
    android:layout_marginStart="25dp" 
    android:layout_marginEnd="25dp" 
    android:paddingTop="10dp" 
    android:paddingBottom="10dp" 
    android:id="@+id/tvAutocompleteListItem"/> 

activity_map.xml

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/search" 
    android:id="@+id/search" 
    android:paddingTop="8dp" 
    android:paddingBottom="8dp" 
    android:paddingStart="10dp" 
    android:paddingEnd="10dp"> 

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="44dp" 
    android:background="@drawable/search_bar" 
    android:id="@+id/search_bar"> 

<ImageButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@drawable/logo_image" 
    android:layout_centerVertical="true" 
    android:layout_marginStart="10dp" 
    android:layout_marginEnd="0dp" 
    android:id="@+id/ibLogoImage" 
    android:contentDescription="@string/logo"/> 

<ImageButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@drawable/search_icon" 
    android:layout_centerVertical="true" 
    android:layout_marginStart="0dp" 
    android:layout_marginEnd="15dp" 
    android:layout_alignParentEnd="true" 
    android:id="@+id/ibSearch" 
    android:contentDescription="@string/search_hint"/> 

<ImageButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/ibClearText" 
    android:layout_toStartOf="@id/ibSearch" 
    android:background="@drawable/clear_text" 
    android:visibility="invisible" 
    android:layout_centerVertical="true" 
    android:layout_marginStart="10dp" 
    android:layout_marginEnd="20dp" 
    android:contentDescription="@string/clear" /> 

<AutoCompleteTextView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/actvSearch" 
    android:hint="@string/search_or_enter_address" 
    android:background="@color/transparent_white" 
    android:textSize="14sp" 
    android:textColor="@color/black" 
    android:completionThreshold="3" 
    android:focusable="true" 
    android:focusableInTouchMode="true" 
    android:layout_centerVertical="true" 
    android:layout_toEndOf="@id/ibLogoImage" 
    android:layout_toStartOf="@id/ibClearText" 
    android:dropDownAnchor="@id/search_bar" 
    android:dropDownVerticalOffset="10dp" /> 

    </RelativeLayout> 
</RelativeLayout> 
+1

Вы также можете установить всплывающий фон AutoCompleteTextView с использованием стиля XML: В 'styles.xml' добавить:' @ style/MyAutoCompleteTextViewTheme 'и добавить' ' –