有人知道教程或示例如何使用s 实现标准Android搜索界面Fragment
吗?换句话说,是否可以SearchManager
在Fragment中添加标准搜索?
有人知道教程或示例如何使用s 实现标准Android搜索界面Fragment
吗?换句话说,是否可以SearchManager
在Fragment中添加标准搜索?
Answers:
简而言之,你不能。有几种原因导致Fragment
无法在中创建搜索界面。
创建可搜索界面时,您必须在Android清单中指定默认的“可搜索活动”。就像您确定的Fragment
那样,没有父母就不能存在Activity
,因此这种分离是不可能的。
如果您已经弄清楚了#1,我假设您问了这个问题,希望有一些神奇的“技巧”可以完成工作。但是,文档指出,
当用户在搜索对话框或窗口小部件中执行搜索时,系统将启动您的可搜索活动,并通过ACTION_SEARCH操作在Intent中向其传递搜索查询。您的可搜索活动从意图的QUERY Extra中检索查询,然后搜索数据并显示结果。
负责提供搜索结果的底层内部系统期望使用Activity
而不是Fragment
; 因此,Activity
不可能实现完全独立于的搜索界面,因为这需要更改底层系统本身。SearchableInfo
如果您不相信我,请查看该类的源代码:)。
话虽如此,要实现与您所描述的内容类似的东西似乎并不难。例如,您可以考虑实现searchable-Activity,以便它接受android.intent.action.SEARCH
意图,并且(而不是立即在中显示结果ListView
)(例如,将搜索查询传递给)Fragment
。例如,考虑以下可搜索的活动:
public class SearchableActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
}
}
/**
* Performs a search and passes the results to the container
* Activity that holds your Fragments.
*/
public void doMySearch(String query) {
// TODO: implement this
}
}
做出搜索请求后,系统将启动您的可搜索活动,执行查询,并将结果传递给某个容器Activity(基于的实现doMySearch
)。然后,容器Activity将这些结果传递给包含的可搜索内容Fragment
,在其中显示结果。该实现所需的工作量比您期望的要多,但是我敢肯定,有一些方法可以使它更加模块化,这似乎是您可以做到的最好的方法。
ps如果使用此方法,则可能必须特别注意将哪些“活动”添加/删除到后堆栈中。有关如何执行此操作的更多信息,请参见这篇文章。
pps您可能还完全忘记了标准搜索界面,只是Fragment
按照下面的Raghav的帖子所述在内实现了简单的搜索。
SearchManager
为Fragment
s 重新实现整个过程,对吗?(或类似的内容)
这是使用片段搜索内容的示例。希望对您有所帮助,这就是您想要的:
public class LoaderCursor extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getFragmentManager();
// Create the list fragment and add it as our sole content.
if (fm.findFragmentById(android.R.id.content) == null) {
CursorLoaderListFragment list = new CursorLoaderListFragment();
fm.beginTransaction().add(android.R.id.content, list).commit();
}
}
public static class CursorLoaderListFragment extends ListFragment
implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> {
// This is the Adapter being used to display the list's data.
SimpleCursorAdapter mAdapter;
// If non-null, this is the current filter the user has provided.
String mCurFilter;
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Give some text to display if there is no data. In a real
// application this would come from a resource.
setEmptyText("No phone numbers");
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2, null,
new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
new int[] { android.R.id.text1, android.R.id.text2 }, 0);
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Place an action bar item for searching.
MenuItem item = menu.add("Search");
item.setIcon(android.R.drawable.ic_menu_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
SearchView sv = new SearchView(getActivity());
sv.setOnQueryTextListener(this);
item.setActionView(sv);
}
public boolean onQueryTextChange(String newText) {
// Called when the action bar search text has changed. Update
// the search filter, and restart the loader to do a new query
// with this filter.
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
getLoaderManager().restartLoader(0, null, this);
return true;
}
@Override public boolean onQueryTextSubmit(String query) {
// Don't care about this.
return true;
}
@Override public void onListItemClick(ListView l, View v, int position, long id) {
// Insert desired behavior here.
Log.i("FragmentComplexList", "Item clicked: " + id);
}
// These are the Contacts rows that we will retrieve.
static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME,
Contacts.CONTACT_STATUS,
Contacts.CONTACT_PRESENCE,
Contacts.PHOTO_ID,
Contacts.LOOKUP_KEY,
};
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// First, pick the base URI to use depending on whether we are
// currently filtering.
Uri baseUri;
if (mCurFilter != null) {
baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
Uri.encode(mCurFilter));
} else {
baseUri = Contacts.CONTENT_URI;
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ))";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, select, null,
Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
// The list should now be shown.
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
}
}
Fragment
所以我不会抱怨。恭喜!:P
onQueryTextChange
方法没有被调用。
使用标准ActionBar SearchView ActionView API进行片段搜索是很有可能的。使用AppCompat支持类v7,也可以将其恢复到Android 2.1(API级别7)。
在您的片段中:
@Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater){
inflater.inflate(R.menu.search, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView sv = new SearchView(((YourActivity) getActivity()).getSupportActionBar().getThemedContext());
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
MenuItemCompat.setActionView(item, sv);
sv.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
System.out.println("search query submit");
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
System.out.println("tap");
return false;
}
});
}
在菜单XML中
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="Search Waste Items"
android:showAsAction="ifRoom|collapseActionView"
nz.govt.app:actionViewClass="android.support.v7.widget.SearchView"
nz.govt.app:showAsAction="ifRoom|collapseActionView" />
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_IF_ROOM); item.setActionView(searchView);
使用AppCompat支持类v7。只是从@Rookie向@David的解决方案中添加一些东西解决方案向解决方案中以简单的方式正常工作,这就是我的片段代码:
MyFragment:
public class MyFragment extends Fragment implements SearchView.OnQueryTextListener {
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// What i have added is this
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
//inflater.inflate(R.menu.main, menu); // removed to not double the menu items
MenuItem item = menu.findItem(R.id.action_search);
SearchView sv = new SearchView(((MainActivity) getActivity()).getSupportActionBar().getThemedContext());
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
MenuItemCompat.setActionView(item, sv);
sv.setOnQueryTextListener(this);
sv.setIconifiedByDefault(false);
sv.setOnSearchClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Utils.LogDebug("Clicked: ");
}
});
MenuItemCompat.setOnActionExpandListener(item, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
Utils.LogDebug("Closed: ");
return true; // Return true to collapse action view
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
Utils.LogDebug("Openeed: ");
return true; // Return true to expand action view
}
});
super.onCreateOptionsMenu(menu,inflater);
}
@Override
public boolean onQueryTextSubmit(String query) {
Utils.LogDebug("Submitted: "+query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
Utils.LogDebug("Changed: "+newText);
return false;
}
}
我添加了onActivityCreated
,因为没有调用setHasOptionsMenu(true);
系统将不会知道此片段需要与菜单进行交互。
然后我删除了线 inflater.inflate(R.menu.main, menu);
因为自从Activity夸大了菜单之后,它就使菜单项加倍,然后Fragment夸大了另一个菜单
感谢@David和@Rookie
与Fragments
您合作时,仍然需要使用和Activity
来控制和分配Fragments
。它Activity
可以像以前一样具有搜索功能。
我最近从基于“普通” Activity
的应用程序切换到了Fragment
基于应用程序的应用程序,并且搜索功能对我来说同样有效。
您是否尝试过尝试,但没有成功?如果是这样,请在您的问题中提供更多详细信息。
编辑:
如果您要进行特定于片段的搜索,请使用方法Fragments
扩展所有接口,并让您的方法调用当前片段的方法。MyFragment
startSearch
Activity
startSearch
startSearch
我想我做到了:您实际上可以使用片段,并在操作栏中添加搜索图标,以便可以在片段内部进行搜索。诀窍是使用操作栏,操作视图,侦听器,加载器和适配器。
尽管它完全绕过了android平台的搜索机制(尽管可以完成一些工作以找到@Alex Lockwood所描述的内容并将搜索传递给片段),但效果很好。它不会对活动产生预期的反应,但可以起作用:用户可以在片段内部进行搜索。
这是代码:
SearchInFragmentActivity
package com.sof.test.searchfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.sof.test.searchfragment.SearchFragment;
import com.sof.test.R;
public class SearchInFragmentActivity extends SherlockFragmentActivity implements TabListener {
private SearchFragment tab1 = new SearchFragment();
private SearchFragment tab2 = new SearchFragment();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.search_in_fragments );
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
createTab( R.string.tab1, R.drawable.ic_menu_search );
createTab( R.string.tab2, R.drawable.ic_menu_search );
getSupportActionBar().setSelectedNavigationItem( 0 );
invalidateOptionsMenu();
}
private void createTab(int tabNameResId, int tabIconResId) {
ActionBar.Tab tab = getSupportActionBar().newTab();
tab.setText( tabNameResId );
tab.setTabListener(this);
getSupportActionBar().addTab(tab);
}// met
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if( ft == null ) {
return;
}//if
View fragmentSlot = findViewById( R.id.fragment );
Fragment newFragment = null;
if( fragmentSlot != null ) {
newFragment = (tab.getPosition() == 0) ? tab1 : tab2;
ft.replace(R.id.fragment, newFragment );
ft.setTransition( FragmentTransaction.TRANSIT_FRAGMENT_FADE);
}//if
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}//class
片段类SearchFragment(我在上面的活动中使用了2个实例)。
package com.sof.test.searchfragment;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.SearchView;
import android.widget.TextView;
import com.sof.test.R;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class SearchFragment extends SherlockListFragment {
private StringLoader loader = null;
private StringAdapter adapter = null;
private List<String> listData = new ArrayList<String>();
private String query;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
createListData();
loader = new StringLoader( getActivity(), this );
adapter = new StringAdapter(listData);
setListAdapter(adapter);
getLoaderManager().initLoader(0, null, new LoaderCallBacks() );
loader.forceLoad();
setHasOptionsMenu( true );
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater ) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate( R.menu.menu_search, menu);
System.out.println( "inflating menu");
final SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
showFilteredItems( newText );
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return;
}//met
private void showFilteredItems( String query ) {
this.query = query;
loader.onContentChanged();
}
private void createListData() {
for( int i = 0; i < 100 ; i ++ ) {
listData.add( "String "+ i );
}
}
public List<String> getData() {
List<String> listFilteredData = new ArrayList<String>();
for( String string : listData ) {
if( query == null || string.contains( query ) ) {
listFilteredData.add( string );
}
}
return listFilteredData;
}//met
private class LoaderCallBacks implements LoaderCallbacks< List<String>> {
@Override
public void onLoadFinished(Loader<List<String>> loader,
List<String> listData) {
adapter.setListData( listData );
}// met
@Override
public void onLoaderReset(Loader<List<String>> listData) {
adapter.setListData( new ArrayList<String>() );
}// met
@Override
public Loader<List<String>> onCreateLoader(int arg0,
Bundle arg1) {
return loader;
}// met
}//class
private class StringAdapter extends ArrayAdapter< String > {
private List<String> listDataToDisplay = new ArrayList<String>();
private LayoutInflater mInflater;
public StringAdapter( List<String> listData ) {
super( getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, listData );
listDataToDisplay = listData;
mInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}//cons
private void setListData( List<String> newListData ) {
this.listDataToDisplay.clear();
this.listDataToDisplay.addAll( newListData );
notifyDataSetChanged();
}//met
/**
* Populate new items in the list.
*/
@Override public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
} else {
view = convertView;
}
((TextView)view.findViewById( android.R.id.text1)).setText( listDataToDisplay.get( position ) );
return view;
}
}//inner class
}//class
class StringLoader extends AsyncTaskLoader<List<String>> {
SearchFragment fragment = null;
public StringLoader(Context context, SearchFragment fragment) {
super(context);
this.fragment = fragment;
}// cons
@Override
public List<String> loadInBackground() {
return fragment.getData();
}// met
}// class
搜索片段的菜单xml文件res / menu / menu_search.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/fragment"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
和xml布局文件res / layout / search_in_fragments.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/fragment"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
SearchView.java
这里看一下源代码。
使用ActionBar
和SearchView
。您将能够处理搜索而无需与“活动”建立任何联系。只需将其设置OnQueryTextListener
为SearchView。
MenuItem item = menu.add("Search");
SearchView sv = new SearchView(getActionBar().getThemedContext());
item.setActionView(sv);
item.setIcon(R.drawable.ic_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
| MenuItem.SHOW_AS_ACTION_IF_ROOM);
sv.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
//...
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
//...
return false;
}
});
有关自定义搜索的更多详细信息,请参见这篇文章。
其他解决方案.....我不喜欢那样。这对我来说更容易。但这是我的主意。我在等待您的意见
public interface SearchImpl {
public void searchQuery(String val);
}
分段
public class MyFragment extends Fragment implements SearchImpl {
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_almanca, container, false);
return view;
}
@Override
public void searchQuery(String val) {
Log.e("getted", val);
}
}
积极性
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Log.e("setted", "" + query);
try {
MyFragment myFGM=new MyFragment();
myFGM.searchQuery(query);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
如果将片段放到ViewPager中,当我不在要提供搜索栏的片段上时,可以通过阻止搜索按钮来做到这一点。进入活动:
@Override
public boolean onSearchRequested() {
if (mPager.getCurrentItem() == mAdapter.getPosition(FragmentType.VIDEO))
return super.onSearchRequested();
else
return false;
}
并且在没有物理搜索按钮的情况下,我在片段中添加了一个操作项,该操作项触发了以下代码:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.search_item) {
return getSherlockActivity().onSearchRequested();
}
return super.onOptionsItemSelected(item);
}
是的,有可能,
请在您的Activity上实现Search视图,Activity中的'onQueryTextChange'也将监听片段中的搜索,您可以在'onQueryTextChange'中检查片段的可见性,如果可见,则可以调用您的片段的搜索方法,它在我的代码中可以完美地工作