简体   繁体   中英

How to open new activity by clicking on SearchView

I created an Android project in which I use search view. I want to open a new activity by clicking the SearchView. When I click icon of SearchView it work perfectly, but when I click in the empty space of the SearchView the keyboard pops up and the new activity is not opening up.

My java code:

searchView=root.findViewById(R.id.search);
searchView.setIconifiedByDefault(true);
searchView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent searchIntent=new Intent(getActivity(),Notification_activity.class);
        getActivity().startActivity(searchIntent);
    }
}); 

My XML:

<SearchView
    android:id="@+id/search"
    android:layout_width="333dp"
    android:layout_height="40dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/search_round_corner"
    android:iconifiedByDefault="false"
    android:queryHint="Enter text to search"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</SearchView>  
searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(this,page,class);
            startActivity(i);
        }
    });
    searchView.setOnCloseListener(new SearchView.OnCloseListener() {
        @Override
        public boolean onClose() {
            //do what you want  searchview is not expanded
            return false;
        }
    });

you should use the query listener for this purpose because after type single word then it will goes to the second activity when you submit the button from keyboard and perform search view functionality. here is the code

 searchView.OnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            String text = s;
            if (text.length() > 0) {
                startActivity(new Intent(Class A Context, Sceond Class B));
            }
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            return false;
        }
    });

use this code,

searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(A.this, B.class));
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM