我想把一个搜索栏作为listview中显示的数据的过滤器。我找不到任何类似的例子。 如果有人能告诉我如何做到这一点或展示一个例子,我将非常感激。
public class ListFragment extends Fragment {
//the GridView
GridView lv;
Bitmap bitmap;
//The list that contains the menuitems (sort)
ArrayList<HashMap<String, String>> menuItems;
ProgressDialog pDialog;
View btnLoadMore;
Spinner spinner;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
//The list that contains the wallappers
ArrayList<Wallpaper> productsList;
//The adapter of the WallPaperList
WallPaperAdapter adapter;
private final String baseurl = AppConstant.BASE_URL;
String list_url;
// url to get all products list
private String url_all_products = baseurl + "get_all_products.php";
private String get_tag_products = baseurl + "get_tag_products.php";
// Flag for current page
int current_page = 0;
int max_pages;
// Prevent loading more items to the GridView twice
boolean isLoading;
//
String sort_order;
String tag;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PAGE = "page";
private static final String TAG_ORDER = "order";
private static final String TAG_TAG = "tag";
private static final String TAG_THUMBURL = "url";
private static final String TAG_TOTAL_PAGE = "total_page";
// products JSONArray
JSONArray products = null;
// listener for sort order
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
Log.v("Selected: ", Integer.toString(position));
if (position == 0){
sort_order = "latest";
} else if (position == 1){
sort_order = "popular";
} else if (position == 2){
sort_order = "oldest";
} else if (position == 3){
sort_order = "alphabet";
}
//"resetting the GridView"
productsList.clear();
if (adapter != null){
adapter.clear();
}
current_page = 0;
isLoading = false;
//TODO footerview is not visible
ConnectivityManager cm =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
new InitialLoadGridView().execute();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.no_internet), Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), ImageGridActivity.class);
startActivity(intent);
}
//}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_listfragment, null);
lv = (GridView)view.findViewById(R.id.listView);
setRetainInstance(true);
setHasOptionsMenu(true);
return view;
}
*@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.pesquisa, menu);
super.onCreateOptionsMenu(menu,inflater);
//Pega o Componente.
SearchView mSearchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
//Define um texto de ajuda:
mSearchView.setQueryHint("teste");
// exemplos de utilização:
return;
}*
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBar actions = getActivity().getActionBar();
actions.setDisplayShowTitleEnabled(false);
// Adapter
SpinnerAdapter spinadapter =
ArrayAdapter.createFromResource(getActivity(), R.array.actions,
//android.R.layout.simple_spinner_dropdown_item);
R.layout.actionbar_spinner_item);
Spinner navigationSpinner = new Spinner(getActivity());
navigationSpinner.setAdapter(spinadapter);
// Here you set navigation listener
navigationSpinner.setOnItemSelectedListener(itemSelectedListener);
actions.setCustomView(navigationSpinner);
if (getActivity().getActionBar().getCustomView().getVisibility() == View.INVISIBLE){
getActivity().getActionBar().getCustomView().setVisibility(View.VISIBLE);
}
actions.setDisplayShowCustomEnabled(true);
//ListFragment is created, so let's clear the imageloader cache
ImageLoader.getInstance().clearMemoryCache();
// Arraylist for GridView
productsList = new ArrayList<Wallpaper>();
//initialize the footer so it can be used
btnLoadMore = View.inflate(getActivity(), R.layout.footerview, null);
if ((getResources().getString(R.string.ad_visibility).equals("0"))){
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) getActivity().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
//TODO Implement and replace old
lv.setOnScrollListener(new OnScrollListener(){
int currentVisibleItemCount;
int currentScrollState;
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentVisibleItemCount = visibleItemCount;
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) {
/*** In this way I detect if there's been a scroll which has completed ***/
/*** do the work for load more date! ***/
if(!isLoading){
isLoading = true;
if (max_pages != current_page){
new loadMoreGridView().execute();
} else {
Log.v("INFO", "Not loading more items because everything is already showing");
}
}
}
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
String pid = productsList.get(position).getPid();
boolean singlepane = MainActivity.getPane();
if(singlepane== true){
/*
* The second fragment not yet loaded.
* Load DetailFragment by FragmentTransaction, and pass
* data from current fragment to second fragment via bundle.
*/
DetailFragment detailFragment = new DetailFragment();
Fragment myListFragment = getFragmentManager().findFragmentByTag("ListFragment");
Bundle bundle = new Bundle();
bundle.putString("TAG_PID",pid);
detailFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction =
getActivity().getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(
R.anim.fadein, R.anim.fadeout, R.anim.fadein, R.anim.fadeout);
//This could use some improvement, but it works, hide current fragment, show new one
fragmentTransaction.hide(myListFragment);
fragmentTransaction.add(R.id.phone_container, detailFragment);
//fragmentTransaction.show(myDetailFragment);
/*
* Add this transaction to the back stack.
* This means that the transaction will be remembered after it is
* committed, and will reverse its operation when later popped off
* the stack.
*/
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
});
}
/**
* Async Task that send a request to url
* Gets new list view data
* Appends to list view
* */
private class loadMoreGridView extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
protected Void doInBackground(Void... unused) {
// increment current page
current_page += +1;
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PAGE, Integer.toString(current_page)));
params.add(new BasicNameValuePair(TAG_ORDER, (sort_order)));
if (tag != null){
params.add(new BasicNameValuePair(TAG_TAG, (tag)));
} else {
list_url = url_all_products;
}
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(list_url, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String thumburl = c.getString(TAG_THUMBURL);
// adding items to arraylist
productsList.add(new Wallpaper(name, thumburl, id));
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
//OUTDATED - Listview seems to automatically keep up with the position
//get GridView current position - used to maintain scroll position
//int currentPosition = lv.getFirstVisiblePosition();
// Appending new data to menuItems ArrayList
adapter.notifyDataSetChanged();
//OUTDATED - Setting new scroll position
//lv.setSelectionFromTop(currentPosition + 1, 0);
if (current_page == max_pages){
adapter.RemoveFooterView();
} else {
adapter.setFooterView(btnLoadMore);
}
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
isLoading = false;
}
}
/**
* Async Task that send a request to url
* Gets new list view data
* Appends to list view
* */
private class InitialLoadGridView extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
getActivity());
pDialog.setMessage(getResources().getString(R.string.wait));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... unused) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_ORDER, (sort_order)));
try { tag = getActivity().getIntent().getExtras().getString("TAG"); } catch (Exception e){}
if (tag != null){
list_url = get_tag_products;
params.add(new BasicNameValuePair(TAG_TAG, (tag)));
} else {
list_url = url_all_products;
}
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(list_url, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
max_pages = json.getInt(TAG_TOTAL_PAGE);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String thumburl = c.getString(TAG_THUMBURL);
// creating new HashMap
//HashMap<String, String> map = new HashMap<String, String>();
// adding items to arraylist
productsList.add(new Wallpaper(name, thumburl, id));
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
public void run() {
// Getting adapter
adapter = new WallPaperAdapter(
getActivity(), productsList);
lv.setAdapter(adapter);
current_page = 0;
if (current_page == max_pages){
adapter.RemoveFooterView();
} else {
adapter.setFooterView(btnLoadMore);
}
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
lv.post(new Runnable() {
public void run() {
//check if last item is visible, in that case, load some more items
if (lv.getLastVisiblePosition() == lv.getAdapter().getCount() -1 &&
lv.getChildAt(lv.getChildCount() - 1).getBottom() <= lv.getHeight() )
{
if(!isLoading){
isLoading = true;
if (max_pages != current_page){
new loadMoreGridView().execute();
Log.v("INFO", "Last Item Visible and more available so loading more");
} else {
Log.v("INFO", "Already showing max pages");
}
}
} else {
Log.v("INFO", "Last Item Not Visible, not loading more");
}
}
});
}
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
Fragment myListFragment = getFragmentManager().findFragmentByTag("ListFragment");
if (myListFragment != null && myListFragment.isVisible()) {
//VISIBLE! =)
Log.d("STATE", "Just became visible!");
getActivity().getActionBar().getCustomView().setVisibility(View.VISIBLE);
getActivity().getActionBar().setDisplayShowTitleEnabled(false);
}
}
public static int convertDpToPixels(float dp, Context context){
Resources resources = context.getResources();
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
resources.getDisplayMetrics()
);
}
public interface MyFragInterface {
public void needsHide();
}
public static boolean isInVisible(GridView scrollView, View view, Rect region, boolean relative)
{
int top = scrollView.getScrollY() + region.top;
int bottom = scrollView.getScrollY() + region.bottom;
if(!relative)
{
// If given region is not relative to scrollView
// i.e 0,0 does not point to first child left and top
top -= scrollView.getTop();
bottom -= scrollView.getTop();
}
Rect rect = new Rect(region);
rect.top = top;
rect.bottom = bottom;
Rect childRegion = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
return Rect.intersects(childRegion, region);
}
}
答案 0 :(得分:1)
将AutoCompleteTextView用于搜索栏对我来说是最简单的方法,以下是示例代码,希望对您有所帮助。
布局Xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment" >
<AutoCompleteTextView
android:id="@+id/search_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search"
android:inputType="text"
android:lines="1"
android:textColor="@color/white"
android:textSize="20sp"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/search_text"
android:background="@color/white"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<ListView
android:id="@+id/countries_list"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
片段:
public static class PlaceholderFragment extends Fragment implements AdapterView.OnItemClickListener {
AutoCompleteTextView searchTextview;
ListView capitalList;
ArrayAdapter searchTextviewAdapter;
private View rootView;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
getActivity().setTitle(" Letsgomo");
searchTextview= (AutoCompleteTextView) rootView.findViewById(R.id.search_text);
capitalList= (ListView) rootView.findViewById(R.id.countries_list);
searchTextviewAdapter=new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,Constants.capitals);
searchTextview.setAdapter(searchTextviewAdapter);
ArrayAdapter capitalAdapter= (ArrayAdapter) searchTextview.getAdapter();
capitalList.setAdapter(capitalAdapter);
capitalList.setOnItemClickListener(this);
return rootView;
}
}