如何将活动中的searchview的输入发送到该活动的视图寻呼机中的片段

Posted

技术标签:

【中文标题】如何将活动中的searchview的输入发送到该活动的视图寻呼机中的片段【英文标题】:How to send input from searchview which is in an activity to fragment which is in the view pager of that activity 【发布时间】:2020-12-27 02:51:58 【问题描述】:

所以我有一个 searchview 放置在一个具有 tablayout 和 viewpager 的活动中。在 viewpager 中,每个选项卡都有一个带有 textview 的片段。我想要做的是从 searchview 获取输入并设置文本带有该输入的文本视图,我似乎无法做到。我试图将来自搜索视图的输入放在一个包中(这是在活动中完成的),然后在 onCreateView() 的片段中获取参数但问题是活动和片段是同时创建的,这意味着来自搜索视图的输入将为空。

这是活动:

public class SearchActivity extends AppCompatActivity 
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
SearchView searchView;
Toolbar toolbar;
ImageButton imageButtonBack;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
    bindUI();
    
    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    viewPagerAdapter.AddFragment(new NewestFragment(), "Newest"); // this line can cause crashes
    viewPagerAdapter.AddFragment(new OldestFragment(), "Oldest"); // this line can cause crashes
    viewPager.setAdapter(viewPagerAdapter);
    tabLayout.setupWithViewPager(viewPager);

    setSearchView();
    setImageButtonBack();


private void setSearchView() 
    searchView.requestFocus();
    View v = searchView.findViewById(R.id.search_plate);
    v.setBackgroundColor(Color.parseColor("#ffffff"));
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() 
        @Override
        public boolean onQueryTextSubmit(String query) 
            Bundle bundle = new Bundle();
            bundle.putString("searchViewText", searchView.getQuery().toString());
            NewestFragment newestFragment = new NewestFragment();
            OldestFragment oldestFragment = new OldestFragment();
            newestFragment.setArguments(bundle);
            oldestFragment.setArguments(bundle);
            searchView.clearFocus();
            return false;
        

        @Override
        public boolean onQueryTextChange(String newText) 
            Bundle bundle = new Bundle();
            bundle.putString("searchViewText", searchView.getQuery().toString());
            NewestFragment newestFragment = new NewestFragment();
            OldestFragment oldestFragment = new OldestFragment();
            newestFragment.setArguments(bundle);
            oldestFragment.setArguments(bundle);
            return false;
        
    );



private void bindUI() 
    imageButtonBack = findViewById(R.id.back);
    tabLayout = findViewById(R.id.tabs);
    viewPager = findViewById(R.id.view_pager);
    searchView = findViewById(R.id.search_view_searchactivity);
    toolbar = findViewById(R.id.toolbar_selected_category);


private void setImageButtonBack() 
    imageButtonBack.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            finish();
        
    );



ViewPager 的适配器:

public class ViewPagerAdapter extends FragmentPagerAdapter 

private final List<Fragment> fragmentList = new ArrayList<>(); // this line can cause crashes
private final List<String> titlesList = new ArrayList<>();

public ViewPagerAdapter(@NonNull FragmentManager fragmentManager) 
    super(fragmentManager);


@NonNull
@Override
public Fragment getItem(int position) 
    return fragmentList.get(position);


@Override
public int getCount() 
    return titlesList.size();


@Nullable
@Override
public CharSequence getPageTitle(int position) 
    return titlesList.get(position);


public void AddFragment(Fragment fragment, String title) 
    fragmentList.add(fragment); // this line can cause crashes
    titlesList.add(title);


@Override
public void notifyDataSetChanged() 
    super.notifyDataSetChanged();


这是片段:

public class NewestFragment extends Fragment 
View view;
TextView textView;

public NewestFragment()



@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
    view=inflater.inflate(R.layout.fragment_search_newest, container, false);
    textView=view.findViewById(R.id.tttttttttttttttttttt);
    try 
        String searchViewText=getArguments().getString("searchViewText");
        textView.setText(searchViewText);
    
    catch (Exception e)
        //something
    
    return view;


【问题讨论】:

【参考方案1】:

片段附加到活动,因此创建第一个活动让我们离开,但我认为您应该使用 MVVM 模式并创建视图模型,然后您可以观察搜索视图并使用该视图模型类更新片段文本视图

https://codelabs.developers.google.com/codelabs/kotlin-android-training-live-data/index.html#0

【讨论】:

【参考方案2】:

要更改由 FragmentPagerAdapter 创建的片段,您应该使用 DynamicFragmentPagerAdapter。参考以下代码。

public class DynamicFragmentPagerAdapter extends PagerAdapter 
    private static final String TAG = "DynamicFragmentPagerAdapter";
  
    private final FragmentManager fragmentManager;
  
    public static abstract class FragmentIdentifier implements Parcelable 
        private final String fragmentTag;
        private final Bundle args;
      
        public FragmentIdentifier(@NonNull String fragmentTag, @Nullable Bundle args) 
            this.fragmentTag = fragmentTag;
            this.args = args;
        
      
        protected FragmentIdentifier(Parcel in) 
            fragmentTag = in.readString();
            args = in.readBundle(getClass().getClassLoader());
        

        @Override
        public void writeToParcel(Parcel dest, int flags) 
            dest.writeString(fragmentTag);
            dest.writeBundle(args);
        
      
        protected final Fragment newFragment() 
            Fragment fragment = createFragment();
            Bundle oldArgs = fragment.getArguments();
            Bundle newArgs = new Bundle();
            if(oldArgs != null) 
                newArgs.putAll(oldArgs);
            
            if(args != null) 
                newArgs.putAll(args);
            
            fragment.setArguments(newArgs);
            return fragment;
        

        protected abstract Fragment createFragment();
    
  
    private ArrayList<FragmentIdentifier> fragmentIdentifiers = new ArrayList<>();

    private FragmentTransaction currentTransaction = null;

    private Fragment currentPrimaryItem = null;

    public DynamicFragmentPagerAdapter(FragmentManager fragmentManager) 
        this.fragmentManager = fragmentManager;
    

    private int findIndexIfAdded(FragmentIdentifier fragmentIdentifier) 
        for (int i = 0, size = fragmentIdentifiers.size(); i < size; i++) 
            FragmentIdentifier identifier = fragmentIdentifiers.get(i);
            if (identifier.fragmentTag.equals(fragmentIdentifier.fragmentTag)) 
                return i;
            
        
        return -1;
    

    public void addFragment(FragmentIdentifier fragmentIdentifier) 
        if (findIndexIfAdded(fragmentIdentifier) < 0) 
            fragmentIdentifiers.add(fragmentIdentifier);
            notifyDataSetChanged();
        
    

    public void removeFragment(FragmentIdentifier fragmentIdentifier) 
        int index = findIndexIfAdded(fragmentIdentifier);
        if (index >= 0) 
            fragmentIdentifiers.remove(index);
            notifyDataSetChanged();
        
    

    @Override
    public int getCount() 
        return fragmentIdentifiers.size();
    

    @Override
    public void startUpdate(@NonNull ViewGroup container) 
        if (container.getId() == View.NO_ID) 
            throw new IllegalStateException("ViewPager with adapter " + this
                    + " requires a view id");
        
    

    @SuppressWarnings("ReferenceEquality")
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) 
        if (currentTransaction == null) 
            currentTransaction = fragmentManager.beginTransaction();
        
        final FragmentIdentifier fragmentIdentifier = fragmentIdentifiers.get(position);
        // Do we already have this fragment?
        final String name = fragmentIdentifier.fragmentTag;
        Fragment fragment = fragmentManager.findFragmentByTag(name);
        if (fragment != null) 
            currentTransaction.attach(fragment);
         else 
            fragment = fragmentIdentifier.newFragment();
            currentTransaction.add(container.getId(), fragment, fragmentIdentifier.fragmentTag);
        
        if (fragment != currentPrimaryItem) 
            fragment.setMenuVisibility(false);
            fragment.setUserVisibleHint(false);
        
        return fragment;
    

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) 
        if (currentTransaction == null) 
            currentTransaction = fragmentManager.beginTransaction();
        
        currentTransaction.detach((Fragment) object);
    

    @SuppressWarnings("ReferenceEquality")
    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) 
        Fragment fragment = (Fragment) object;
        if (fragment != currentPrimaryItem) 
            if (currentPrimaryItem != null) 
                currentPrimaryItem.setMenuVisibility(false);
                currentPrimaryItem.setUserVisibleHint(false);
            
            fragment.setMenuVisibility(true);
            fragment.setUserVisibleHint(true);
            currentPrimaryItem = fragment;
        
    

    @Override
    public void finishUpdate(@NonNull ViewGroup container) 
        if (currentTransaction != null) 
            currentTransaction.commitNowAllowingStateLoss();
            currentTransaction = null;
        
    

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) 
        return ((Fragment) object).getView() == view;
    

    @Override
    public Parcelable saveState() 
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("fragmentIdentifiers", fragmentIdentifiers);
        return bundle;
    

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) 
        Bundle bundle = ((Bundle)state);
        bundle.setClassLoader(loader);
        fragmentIdentifiers = bundle.getParcelableArrayList("fragmentIdentifiers");
    

【讨论】:

以上是关于如何将活动中的searchview的输入发送到该活动的视图寻呼机中的片段的主要内容,如果未能解决你的问题,请参考以下文章

如何为我的 GridView 包含 SearchView?

用户输入后禁用edittext searchview

如何以编程方式关闭 SearchView?

使用Recyclerview的searchview EditText

如何将多个图像发送到android中的另一个活动?

如何将当前位置从一项活动发送到另一项活动?