I want to implement SearchView with multiple fragments present in a viewPager. All fragemnts contains lists and I want to filter those lists and create a new ListView which has
Below hint may help you
public class AnyActivity extends AppCompatActivity {
private ListenFromActivity activityListener1;
}
then define interface with separate file
public interface ListenFromActivity {
void doSearchInFragment(String SearchKey);
}
now in your fragment
public class Connections extends Fragment implements ListenFromActivity
{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
((AnyActivity)Objects.requireNonNull(getActivity())).setActivityTab1Listener(Connections.this);
}
@Override
public void doSearchInFragment(String SearchKey) {
//pass to any network or local call.
}
}
If You wanna search your query to all fragment must use Viewmodel with Livedata. Set Your Query in Livedata then Your Livedata Observe on all Your Fragment.
This Code in viewPager side
val searchLiveData = MutableLiveData<String>()
searchLiveData.postValue("query")
This code in all Fragments
mainViewModel.searchLiveData.observe(viewLifecycleOwner, Observer { query ->
//Add your code
})
//1
val liveData: MutableLiveData<Any>()
//2
liveData.value = "Hello"
//3
liveData.observe(this, Observer {
// Update UI
})
I got my fragments have list with one Searchview working by using following code.. Place the code in each fragment where you want to
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser)
{
search_bar.setOnQueryTextListener(this);
if(listAdapter!=null)
listAdapter.getFilter().filter(search_bar.getQuery());
}
}
Screenshots: