Tengo algunos problemas con cerrar mi SearchView
El primero: SOLUCIONADO
Cuando busco en mi listview
y entro en la Activity
que encuentra, al volver atrás mi SearchView
sigue abierta ¿Cómo puedo hacer que se cierre automáticamente?
El segundo: SOLUCIONADO
Para abrir mi SearchView
hago click sobre el icono (lupa) que tengo en menu/menu_buscar
con ID action_search
¿Cómo puedo hacer que para qué cuando este abierta y haga click se cierre?
Y por último: SOLUCIONADO he creado este código para poder cerrar mi SearchView
desde el botón atrás del móvil, pero cómo puedo hacer para que cuando este cerrada su función sea la que es por defecto, ir atrás en mi Activity
Código para cerrar la SearchView
haciendo click en el botón atrás del móvil
@Override
public void onBackPressed() {
searchView.closeSearch();
}
Código para las dos primeras cuestiones:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cat_shishas);
icon_cat_shi = (ImageView) findViewById(R.id.icon_cat_shi);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imagenes = new ArrayList();
for (Integer pos : new int[]{
R.drawable.icon_1,
R.drawable.icon_2,
}) {
imagenes.add(pos);
}
final ListView lista = (ListView) findViewById(R.id.listview_shi);
titulo = new ArrayList();
for (String tit : getResources().getStringArray(R.array.as1)) {
titulo.add(tit);
}
adapter = new IndexAdapter(this, new int[]{0, 1});
lista.setAdapter(adapter);
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView adapterView, View view, int posicion, long l) {
switch ((Integer) adapter.getItem(posicion)) {
case 0:
Intent aln = new Intent(getApplicationContext(), Assq.class);
startActivity(aln);
break;
case 1:
Intent caer = new Intent(getApplicationContext(), Aassa.class);
startActivity(caer);
break;
}
}
});
searchView = (MaterialSearchView) findViewById(R.id.search_view);
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewShown() {
}
@Override
public void onSearchViewClosed() {
adapter.clear();
adapter.set(titulo.toArray(new String[0]));
}
});
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (newText != null && !newText.isEmpty()) {
List<String> lstFound = new ArrayList();
for (String item : titulo) {
if (item.contains(newText))
lstFound.add(item);
}
String[] subTitulo = lstFound.toArray(new String[0]);
adapter.set(subTitulo);
} else {
adapter.set(titulo.toArray(new String[0]));
return true;
}
return true;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_buscar,menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_search:
icon_cat_shi.setVisibility(View.INVISIBLE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
ACTUALIZACIÓN:
La primera y última cuestión han quedado solucionadas, me falta la segunda.
Cuando hago click en action_search
se abre la SearchView
hasta ahí todo OK, pero quiero que cuando este abierta su función sea cerrar la SearchView
cómo podría hacerlo?
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_buscar,menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
return true;
}
ACTUALIZACIÓN 3: para @StefanNolde
He creado una nueva clase llamada MyMSView
import com.miguelcatalan.materialsearchview.MaterialSearchView;
public class MyMSView extends MaterialSearchView {
//////////// creo campo MenuItem
MenuItem mMenuItem;
//////////////// creo el constructor que me pide Android Studio
public MyMSView(Context context) {
super(context);
}
@Override
public void setMenuItem(MenuItem menuItem) {
this.mMenuItem = menuItem;
mMenuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (isSearchOpen()){
closeSearch();
} else {
showSearch();
}
return true;
}
});
}
}
Activity
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import otrointento.dos.MyMSView;
public class Cat_shishas extends AppCompatActivity {
MyMSView searchView;
IndexAdapter adapter;
ImageView icon_cat_shi;
ArrayList<String> titulo;
ArrayList<Integer> imagenes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cat_shishas);
icon_cat_shi = (ImageView) findViewById(R.id.icon_cat_shi);
imagenes = new ArrayList();
for (Integer pos : new int[]{
R.drawable.ic_launcher,
R.drawable.ic_launcher,
}){ imagenes.add(pos); }
final ListView lista = (ListView) findViewById(R.id.listview_shi);
titulo =new ArrayList();
for (String tit : getResources().getStringArray(shishas)){
titulo.add(tit);
}
adapter = new IndexAdapter(this, new int[]{0, 1});
lista.setAdapter(adapter);
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView adapterView, View view, int posicion, long l) {
switch ((Integer)adapter.getItem(posicion)) {
case 0:
Intent alas = new Intent(getApplicationContext(), Clase1.class);
if (searchView.isSearchOpen()) searchView.closeSearch();
startActivity(alas);
break;
case 1:
Intent cssa = new Intent(getApplicationContext(), Clase2.class);
if (searchView.isSearchOpen()) searchView.closeSearch();
startActivity(cssa);
break;
}
}
});
searchView = (MyMSView) findViewById(R.id.search_view);
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewShown() {
icon_cat_shi.setVisibility(View.INVISIBLE);
}
@Override
public void onSearchViewClosed() {
//If closed Search View , lstView will return default
adapter.clear();
adapter.set(titulo.toArray(new String[0]));
icon_cat_shi.setVisibility(View.VISIBLE);
}
});
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (newText != null && !newText.isEmpty()) {
List<String> lstFound = new ArrayList();
for (String item : titulo) {
if (item.contains(newText))
lstFound.add(item);
}
String[] subTitulo = lstFound.toArray(new String[0]);
adapter.set(subTitulo);
} else {
//if search text is null
//return default
adapter.set(titulo.toArray(new String[0]));
return true;
}
return true;
}
});
}
@Override
public void onBackPressed() {
if (searchView.isSearchOpen()) {
searchView.closeSearch();
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_buscar,menu);
MenuItem item = menu.findItem(action_search);
searchView.setMenuItem(item);
return true;
}
Layout:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/activity_cat_shishas">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="184dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:expandedTitleGravity="bottom|center">
<com.miguelcatalan.materialsearchview.MaterialSearchView
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:searchBackground="@drawable/contorno_design"
app:searchSuggestionBackground="@color/colorPrimary"
app:searchCloseIcon="@drawable/ic_action_navigation_close_inverted"
app:searchBackIcon="@drawable/ic_action_navigation_arrow_back_inverted"
app:searchSuggestionIcon="@drawable/ic_suggestion"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF"
android:layout_marginEnd="70dp"
android:layout_marginStart="70dp"
android:layout_marginTop="10dp"
android:elevation="2dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/icon_shi"
android:id="@+id/icon_cat_shi"
android:layout_gravity="top|center"
/>
<View
android:background="#ffffffff"
android:id="@+id/linea1"
android:layout_gravity="center"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_width="380dp" />
<View
android:background="#ffffffff"
android:id="@+id/linea2"
android:layout_gravity="center"
android:layout_height="1dp"
android:layout_marginTop="80dp"
android:layout_width="380dp" />
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
android:layout_marginTop="10dp" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f7f7f7"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/cat_shi_vertical">
<View
android:background="@drawable/degradado"
android:id="@+id/separador1"
android:layout_width="fill_parent"
android:layout_height="18dp"
android:layout_gravity="start" />
<ListView
android:layout_width="match_parent"
android:id="@+id/listview_shi"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:divider="@drawable/list_divider"
android:layout_height="1650dp" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
Como bien me avisaste recibo ClassCastException
Logcat
02-09 23:26:08.360 14718-14718/otrointento.dos E/AndroidRuntime: FATAL EXCEPTION: main
Process: otrointento.dos, PID: 14718
java.lang.RuntimeException: Unable to start activity ComponentInfo{otrointento.dos/otrointento.dos.categorias.Cat_shishas}: java.lang.ClassCastException: com.miguelcatalan.materialsearchview.MaterialSearchView cannot be cast to otrointento.dos.MyMSView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2680)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2741)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6176)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Caused by: java.lang.ClassCastException: com.miguelcatalan.materialsearchview.MaterialSearchView cannot be cast to otrointento.dos.MyMSView
at otrointento.dos.categorias.Cat_shishas.onCreate(Cat_shishas.java:83)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2633)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2741)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6176)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
ACTUALIZACIÓN 2:
logcast
02-10 02:10:42.622 16441-16441/otrointento.dos E/AndroidRuntime: FATAL EXCEPTION: main
Process: otrointento.dos, PID: 16441
java.lang.RuntimeException: Unable to start activity ComponentInfo{otrointento.dos/otrointento.dos.categorias.Cat_shishas}: android.view.InflateException: Binary XML file line #21: Binary XML file line #21: Error inflating class otrointento.dos.MyMSView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2680)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2741)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6176)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Caused by: android.view.InflateException: Binary XML file line #21: Binary XML file line #21: Error inflating class otrointento.dos.MyMSView
Caused by: android.view.InflateException: Binary XML file line #21: Error inflating class otrointento.dos.MyMSView
Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]
at java.lang.Class.getConstructor0(Class.java:2204)
at java.lang.Class.getConstructor(Class.java:1683)
at android.view.LayoutInflater.createView(LayoutInflater.java:618)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:288)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at otrointento.dos.categorias.Cat_shishas.onCreate(Cat_shishas.java:42)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2633)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2741)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6176)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)