Как добавить панель поиска с редактированием текста на панели инструментов
Я хочу добавить строку поиска с текстом редактирования на панели инструментов, как показано ниже.
![введите описание изображения здесь]()
Моя панель инструментов .xml: -
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="@style/ThemeOverlay.AppCompat.Light" >
<EditText
android:id="@+id/searchEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</android.support.v7.widget.Toolbar>
После добавления текста редактирования на панели инструментов моя панель инструментов выглядит следующим образом: -
![введите описание изображения здесь]()
Ответы
Ответ 1
как я понимаю, я надеюсь, что этот код может помочь вам...
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray_500"
android:orientation="vertical"
android:gravity="center|right">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/white"
android:orientation="horizontal"
android:gravity="center|right">
<TextView
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_weight="8"
android:layout_margin="5dp"
android:text="snap deal"
android:gravity="center" >
</TextView>
<TextView
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_weight="2"
android:layout_margin="5dp"
android:ems="10"
android:text="Img"
android:gravity="center" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/white"
android:gravity="center|right">
<EditText
android:id="@+id/editMobileNo"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="5dp"
android:background="@drawable/login_edittext"
android:ems="10"
android:hint="Find your dil ki deal"
android:drawableLeft="@drawable/search"
android:gravity="center" >
</EditText>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.Toolbar>
это настраиваемая форма для EditText login_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="270"
android:endColor="@color/white"
android:startColor="@color/white" />
<stroke
android:width="1dp"
android:color="@color/gray_500" />
<corners
android:radius="1dp" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
</item>
</selector>
![введите описание изображения здесь]()
Это всего лишь эскиз... вам нужно изменить цвет, размер, изображение и т.д.
Ответ 2
Я считаю, что представление, которое вы ищете, является SearchView
. Вы можете определить в своем menu.xml
что вы хотите добавить его в свой ActionBar/ToolBar. Как это:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/search"
android:icon="@drawable/search_icon"
android:title="@string/search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
</menu>
Вернувшись к своей Деятельности или Фрагменту, вы можете манипулировать поведением вида поиска и внешним видом:
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem searchViewMenuItem = menu.findItem(R.id.search);
searchView = (SearchView) searchViewMenuItem.getActionView();
ImageView v = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_button);
v.setImageResource(R.drawable.search_icon); //Changing the image
if (!searchFor.isEmpty()) {
searchView.setIconified(false);
searchView.setQuery(searchFor, false);
}
searchView.setQueryHint(getResources().getString(R.string.search_hint));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
//Do your search
}
@Override
public boolean onQueryTextChange(String newText) {
if(newText.isEmpty()) clearSearch();
return false;
}
});
}
Это более простой способ сделать это. Наиболее рекомендуемый способ заключается в том, чтобы на самом деле иметь активность, отвечающую вашим поисковым намерениям. Для получения дополнительной информации об этом имени посетите: http://developer.android.com/intl/pt-br/guide/topics/search/search-dialog.html
Ответ 3
Просто добавьте текст редактирования как часть вашей панели инструментов, примерно так:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/primaryColor"
android:elevation="4dp">
<EditText
android:id="@+id/searchEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</android.support.v7.widget.Toolbar>
Ответ 4
вы можете прямо разместить searchview в свой файл activity.xml внутри вашей панели инструментов и инициализировать его. Я думаю, вы получите желаемый макет.
Ответ 5
Мне нравится решение TextEdit выше для обратной совместимости.
Вот еще две вещи, чтобы рассмотреть, чтобы достигнуть оригинального примера:
- В определении Activity xml TextEdit добавьте:
андроид: drawableStart = "@андроид: рисуем /ic_menu_search"
// To add the magnifying glass.
Android: намек = "@строка /Search_Txt"
// To add the hint message.
-
В XML файл String добавьте:
string name = "Search_Txt"> Найдите свою сделку
// Customize your message here.
Примечание. Для альтернативы SearchView потребуется API 21.
Наслаждаться.