带标签的Android搜索

时间:2018-08-27 17:52:46

标签: android android-recyclerview android-tablayout

我正在尝试对我的应用程序执行某种搜索,以过滤TabLayout和ViewPager中包含片段的数据。

带有ViewPager和TabLayout的MyFragment的一部分:

@Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ...
        search = view.findViewById(R.id.search);
        pager = view.findViewById(R.id.pager);
        TabLayout tabs = view.findViewById(R.id.tab);

        MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());

        viewModel.data.observe(this, entities ->
        {
            if (entities != null) {
                repo.updateData(entities);
                pager.setAdapter(adapter);
                tabs.setupWithViewPager(pager);
            }
        });

        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() >= 2) {
for (int i = 0; i < 3; i++) {
                ContactsListFragment fragment = (ContactsListFragment) adapter.instantiateItem(pager, i);
                if (fragment.isAdded()) fragment.setSearch(s);
            }
}
                else {for (int i = 0; i < 3; i++) {
                MyListFragment fragment = (MyListFragment) adapter.instantiateItem(pager, i);
                if (fragment.isAdded()) fragment.setSearch("");
            }
}
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        return view;
    }

当我尝试将String对象传递给MyListFragment(仅内部包含RecyclerView)并更改适配器中的数据时,它说我的RecyclerView为空。

如何将String对象传递给ViewPager的每个片段并过滤其中的数据?

1 个答案:

答案 0 :(得分:0)

我找到了答案。我试图获取不正确的Fragment实例。

旧代码部分(从适配器获取片段):

MyListFragment fragment = (MyListFragment) adapter.instantiateItem(pager, i);

新代码部分(从FragmentManager中获取片段):

MyListFragment fragment = (MyListFragment) getSupportFragmentManager()
                    .findFragmentByTag("android:switcher:" + R.id.pager + ":" + pager.getCurrentItem());