SearchView with multiple fragments using viewpager in android

前端 未结 3 1751
死守一世寂寞
死守一世寂寞 2021-02-02 16:06

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

相关标签:
3条回答
  • 2021-02-02 16:34

    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.
        }
    }
    
    0 讨论(0)
  • 2021-02-02 16:48

    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  
    })
    
    0 讨论(0)
  • 2021-02-02 16:59

    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:

    0 讨论(0)
提交回复
热议问题