looking for some solutions? You are welcome.

SOLVED: Fragment SearchView for ListView

Edward Brand:

Trying to add search functionality to my ListView in a fragment. I have a ListView adapter class from a tutorial which adds an image(first letter of the item as an icon). When I type into the search field nothing happens. The following is my simplified fragment code where the problem rises (I think):

private View view;
private ListView instrumentListView;
private SearchView searchinstrumentText;
private String[] instrumentItems={"1", "2", "3", "4", "5"};
private ArrayList<String> instrumentList;
private ArrayAdapter instrumentAdapter;

public InstrumentListFragment(){
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle 
savedInstanceState) {


    View view = inflater.inflate(R.layout.fragment_instrumentlist, container, 
false);
    final ListView instrumentView = (ListView) 
view.findViewById(R.id.instrumentListView);
    SearchView searchinstrumentText=(SearchView) 
view.findViewById(R.id.searchinstrumentText);


    //The following is a custom adapter!
    final ArrayList<String> instrumentList = new ArrayList<String>();
    instrumentList.addAll( Arrays.asList(instrumentItems));
    final ArrayAdapter instrumentAdapter = new ListAdapter(getActivity(), 
R.layout.custom_listview, instrumentList);
    instrumentView.setAdapter(instrumentAdapter);


    //SEARCH
    searchinstrumentText.setQueryHint("Search");
    searchinstrumentText.setOnQueryTextListener(new 
SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String txt) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String txt) {
            instrumentAdapter.getFilter().filter(txt);
            return false;
        }
    });
    return view;
}

and here is my XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".InstrumentListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_fragment">

<SearchView
    android:id="@+id/searchinstrumentText"
    style="@style/TextEdit"
    android:ems="10"
    android:hint="Search" />

<ListView
    android:id="@+id/instrumentListView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/searchinstrumentText"
    android:layout_marginTop="1dp" />


</RelativeLayout>

I would really appreciate some guidance as I am new to app developing. I didn't include my adapter code because I don't think it's relevant (I might be wrong but it does work). Thank you in advance, Edward



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent