Sanjeev Yadav
Sanjeev Yadav

Reputation: 3031

Implementing list search view inside SherlockFragment

I have created ViewPagerAdapter and I am calling Fragment2 inside veiewpageradapter, but I need to create list search view inside fragment2.

public class ViewPagerAdapter extends FragmentPagerAdapter {

@Override
public Fragment getItem(int arg0) {
    switch (arg0) {

    // Open Fragment1.java
    case 0:
        Fragment1 fragment1 = new Fragment();
        return fragment1;

    // Open Fragment2.java
    case 1:
        Fragment2 fragment = new Fragment2();
        return fragment;


    return null;
}



}   

My fragment class

public class Fragment2 extends SherlockFragment {


 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Get the view from fragmenttab2.xml
    View view = inflater.inflate(R.layout.fragment2, container, false);


   //NEED TO CALL LIST SEARCH VIEW       




    return view;
}


}

Is it possible to call list search view inside onCreateView()?

Upvotes: 1

Views: 789

Answers (1)

user872230
user872230

Reputation:

In the Fragment class you need to add this:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu, menu);

    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setQueryHint("Search");
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) {
            if(!TextUtils.isEmpty(newText)) {
                // Call filter here
                return true;
            }

            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            // Do something
            return true;
        }
    });
}

Add this line to the onCreateView method in the Fragment class (before the return statement, obviously)

this.setHasOptionsMenu(true);

And finally, here is the menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/search"
        android:title="@string/menu_search"
        android:icon="@drawable/ic_action_search"
        android:showAsAction="always"
        android:actionViewClass="com.actionbarsherlock.widget.SearchView" />
</menu>

Hope this helps.

You should also read:

Upvotes: 1

Related Questions