Problems closing SearchView

4

I have some problems with closing my SearchView

The first: SOLVED

When I search in my listview and enter the Activity that 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 in menu/menu_buscar with ID action_search How can I make it so that when it is open and clicks it closes?

And finally : SOLVED I created this code to be able to close my SearchView from the back button on the mobile, but how can I do so that when it is closed its function is the default, go back in my Activity

Code to close the SearchView by clicking on the button back 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, the second one is missing. When I click on action_search the SearchView opens up there all OK, but I want that when it is open its function is to close the 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: for @StefanNolde

I created a new class called 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>

As you kindly told me, I receive 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)
    
asked by UserNameYo 08.02.2017 в 17:33
source

2 answers

2

for case 1

to close the searchView before leaving for other activities:

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);
                if (searchView.isSearchOpen()) searchView,closeSearch();
                startActivity(aln);
                break;
            case 1:
                Intent caer = new Intent(getApplicationContext(), Aassa.class);
                if (searchView.isSearchOpen()) searchView,closeSearch();
                startActivity(caer);
                break;
        }
    }
});

for case 2

in onOptionsItemSelected you can differentiate:

if (null!=searchView && searchView.isSearchOpen()){
    searchView.close();
    return true;
} else {
    // cosas que hacer para la busqueda
    return true;
}

But since the searchView covers the menu, you have to modify the listener in MaterialSearchView. Checking the source code of MaterialSearchView , the following should solve what you want to do:

// vamos a hacer una subclase de MaterialSearchView:
public class MyMSView extends MaterialSearchView{

    public MyMSView(Context context) {
        this(context, null);
    }

    public MyMSView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyMSView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs);

    }

    @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;
            }
        });
    }
}

then you use MyMSView instead of MaterialSearchView in your activity.

for case 3 close in onBackPressed()

If I understand you well, you want to keep the original function of onBackPressed() . If you want that, you should not forget in an @Override to also call the original function:

@Override
public void onBackPressed() {
    if (searchView.isSearchOpen()) {
        searchView.closeSearch();
    }
    super.onBackPressed();
}

or if you want to do the one or the other thing, dependent if the searchView is open:

@Override
public void onBackPressed() {
    if (searchView.isSearchOpen()) {
        searchView.closeSearch();
    } else {
        super.onBackPressed();
    }
}

Update

Your offender is here:

Caused by: java.lang.ClassCastException: com.miguelcatalan.materialsearchview.MaterialSearchView cannot be cast to otrointento.dos.categorias.Cat_prueba$MyMSView
   at otrointento.dos.categorias.Cat_prueba.onCreate(Cat_prueba.java:188)

you have to change the casts:

searchView = (MaterialSearchView) 

it has to be

searchView = findViewById(R.id.search_view);

and searchView has to be declared as MyMSView. A part where no you have to change to the name of the new class is:

new MyMSView.OnQueryTextListener()

that does NOT work, you have to keep declaring MaterialSearchView.OnClickListener() , because the inner class is still the same. When one makes a subclass, it does not take all the static aspects. In general, while correcting errors, remember:

  • The instance (new Class () ...) has to be your new class.
  • The variable you should declare as your new class
  • the layout must have the <tag> of your new class
  • in the static context you still use MaterialSearchView , for example in names of internal classes

Update 2

import com.miguelcatalan.materialsearchview.MaterialSearchView;
// aquí tienes que importar tu clase (si no es en el mismo paquete)

public class Cat_shishas extends AppCompatActivity {

    ///////////////// cambio MaterialSearchView searchView; por:
    // no. "Clase variable;" - eso es la declaracion.
    //MaterialSearchView MyMSView;
    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);

/////////////////////// cambio searchView por MyMSView
// de nuevo no, el nombre de tu variable estaba bien, la clase tiene que ser la tuya

                        if (searchView.isSearchOpen()) searchView.closeSearch();
                        startActivity(alas);
                        break;
                    case 1:
                        Intent cssa = new Intent(getApplicationContext(), Clase2.class);

/////////////////////// cambio searchView por MyMSView
// y de nuevo véase arriba

                        if (searchView.isSearchOpen()) searchView.closeSearch();
                        startActivity(cssa);
                        break;
                }
            }
        });

// si eso aquí te da una ClassCastException, revisa tu layout 
        searchView = (MyMSView) findViewById(R.id.search_view);

/////////////////////// cambio searchView por MyMSView        
// MaterialSearchView aqui esta bien, porque nos referímos a la clase interna de MaterialSearchView
        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);
            }
        });

/////////////////////// cambio searchView por MyMSView
// idem
        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);
                    }

                    // usemos otro nombre de variable para mas claridad
                    // aun que diferenciemos entre this.titulo y titulo, así queda mas obvio
                    String[] subTitulo = lstFound.toArray(new String[0]);
                    // de nuevo, quedemos con el mismo adapter.
                    adapter.set(subTitulo);
                } else {
                    //if search text is null
                    //return default
                    // y de nuevo ;)
                    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;
    }
}

I get the impression that you do a lot of "monkey patching", using code of examples that deep down you do not understand well. I recommend you to get a little in the basics, basic Java, POO concepts. Look here:

Do not be afraid of OOP!

Update 3

your problem is that:

        <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" />

must be:

        <otrointento.dos.MyMSView
            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" />

Update 4

The constructors were missing in MyMSView . I've updated it up.

    
answered by 09.02.2017 / 00:49
source
0

1) Actually what you are opening is the menu and not the SearchView, to detect is opening the SearchView you can add a Listener, you get the reference of the ImageView and change its visibility:

SearchView searchView = (SearchView) findViewById(R.id.searchView);
    searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            icon_cat_shi.setVisibility(View.INVISIBLE);

        }
    });

2) to close it programmatically in another action in addition to activating the "return" button you can implement that when it is opened another Activity is closed by:

 if (!searchView.isIconified()) {
        searchView.onActionViewCollapsed();
 } 
    
answered by 08.02.2017 в 17:56