I have some problems with closing mySearchView
The first: SOLVED
When I search in my listview
and enter the Activity
one it finds, when I go back my SearchView
is still open. How can I make it close automatically?
The second: SOLVED
To open my SearchView
, I click on the icon (magnifying glass) that I have menu/menu_buscar
with ID action_search
. How can I make it so that when it is open and I click it closes?
And finally : SOLVED I have created this code to be able to close my SearchView
from the back button of the mobile, but how can I make it so that when it is closed its function is the one that is by default, go back in myActivity
Code to close the SearchView
by clicking on the back button of the mobile
@Override
public void onBackPressed() {
searchView.closeSearch();
}
Code for the first two questions:
@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);
}
}
UPDATE:
The first and last question have been solved, I need the second. When I click on action_search
it opens SearchView
up to there everything OK, but I want that when it is open its function is to close it SearchView
how could I do it?
@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;
}
UPDATE 3: to @StefanNolde
I have created a new class calledMyMSView
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>
How well did you notify me?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)
UPDATE 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)
para caso 1
para cerrar el searchView antes de partir a otras actividades:
para caso 2
en
onOptionsItemSelected
puedes diferenciar:Pero como el searchView te tapa el menu, tienes que modificar el listener en MaterialSearchView. Revisando el código fuente de
MaterialSearchView
, lo siguiente te debería solucionar lo que quieres hacer:luego usas
MyMSView
en ves deMaterialSearchView
en tu actividad.para caso 3 cerrar en
onBackPressed()
si te entiendo bien, quieres mantener la función original de
onBackPressed()
. Si quieres eso, no deberías olvidar en un @Override de tambien llamar la función original:o si quieres hacer la una o la otra cosa, dependiente si el
searchView
esta abierto:actualisación
Tu delincuente se encuentra aquí:
tu tienes que cambiar los casts:
tiene que ser
y searchView tiene que ser declarado como MyMSView. Una parte donde no tienes que cambiar al nombre de la nueva clase es:
eso NO funciona, tienes que seguir declarando
MaterialSearchView.OnClickListener()
, porque la clase interna sigue siendo lo mismo. Cuando uno hace una subclase, no se lleva todos los aspectos estáticos. En general mientras corriges los errores, recuerda:<tag>
de tu nueva claseMaterialSearchView
, por ejemplo en nombres de clases internosactualisación 2
Me da la impresión que haces mucho "monkey patching", usando código de ejemplos que en el fondo no entiendes bien. Te recomiendo de meterte un poco en los básicos, Java basico, conceptos de POO. Mira aqui:
¡No temas a la POO!
actualisación 3
tu problema es eso:
tiene que ser:
actualisación 4
Faltaban los constructores en
MyMSView
. lo he actualizado arriba.1) Actually what you are opening is the menu and not the SearchView, to detect if the SearchView is opening you can add a Listener, you get the ImageView reference and change its visibility:
2) para cerrarlo programaticamente en otra acción además de activar el botón "regreso" puedes implementar que cuando es abre otra Activity se cierre mediante: