如何在片段中实现Android搜索功能?

时间:2016-12-19 17:50:47

标签: java android android-fragments arraylist

我正在创建一个应用程序,允许用户将自己的单词添加到ArrayList,并且必须能够搜索它们。我已将搜索按钮放在操作栏上。但是当我输入一个单词时,它并没有向我显示我搜索过的单词。这是我的代码片段。 这是一个包含ArrayList

的片段
public class FamilyFragment extends Fragment {
public FamilyFragment() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_word_list, container, false);
    setHasOptionsMenu(true);

    ArrayList<Word> words = new ArrayList<Word>();
    words.add(new Word("Father", "baba", R.drawable.family_father));
    words.add(new Word("Mother", "mama", R.drawable.family_mother));
    words.add(new Word("Son", "er zi", R.drawable.family_son));
    words.add(new Word("Daugther", "nu er", R.drawable.family_daughter));
    words.add(new Word("Older brother", "gege", R.drawable.family_older_brother));
    words.add(new Word("Younger brother", "didi", R.drawable.family_younger_brother));
    words.add(new Word("Older Sister", "jiejie", R.drawable.family_older_sister));
    words.add(new Word("Younger Sister", "meimei", R.drawable.family_younger_sister));
    words.add(new Word("Friend", "peng you"));

    WordAdapter adapter = new WordAdapter(getActivity(), words, R.color.category_family);

    ListView listView = (ListView) rootView.findViewById(R.id.list);

    listView.setAdapter(adapter);

    return rootView;

我希望能够使用此方法搜索arraylist

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    MenuItem item = menu.add("Search");

    item.setIcon(R.drawable.color_black); // sets icon
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    SearchView sv = new SearchView(getActivity());

    int id = sv.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
    TextView textView = (TextView) sv.findViewById(id);
    textView.setHint("Search");


    // implementing the listener
    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            if (s.length() < 4) {
                    Toast.makeText(getActivity(),
                            "Your search query must not be less than 3 characters",
                            Toast.LENGTH_LONG).show();
                    return true;
                } else {
                    // doSearch(s);
                    return false;
                }
            }


        @Override
        public boolean onQueryTextChange(String newText) {
            return true;
        }
    });
    item.setActionView(sv);
}

但是当我提交这个词时,什么都没有出现。谢谢你提前

0 个答案:

没有答案