2013-07-27 36 views
1

我創建了ViewPagerAdapter,我在veiewpageradapter中調用Fragment2,但我需要在fragment2內創建列表搜索視圖。在SherlockFragment中實現列表搜索視圖

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



} 

我的片段類

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


} 

是否可以調用內部onCreateView列表搜索視圖()?

回答

2

在您需要添加這個片段類:

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

此行添加到片段中的類onCreateView方法(return語句之前,很明顯)

this.setHasOptionsMenu(true); 

最後,這裏是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> 

希望這會有所幫助。

你也應該閱讀: