Я работаю над проектом переводчика языка. В котором я использую несколько фрагментов с TabLayout и Viewpager
. Я также использую RecyclerView
для отображения списков. Каждый фрагмент имеет свой собственный экземпляр класса RecyclerViewAdapter. Но я хочу применить вид поиска в действии. В котором я хочу отфильтровать результаты от всех фрагментов. Но это не работает. Если вы хотите узнать больше о моем проекте, просто дайте мне знать.
Здесь мой MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.fidu.learnchinese.Fragments.ClothesFragment;
import com.fidu.learnchinese.Fragments.ColorFragment;
import com.fidu.learnchinese.Fragments.EatingOutFragment;
import com.fidu.learnchinese.Fragments.FamilyFragment;
import com.fidu.learnchinese.Fragments.GreetingFragment;
import com.fidu.learnchinese.Fragments.NumberFragment;
import com.fidu.learnchinese.Adapters.PagerAdpater;
import com.fidu.learnchinese.R;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private TabLayout mTabLayout;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar=findViewById(R.id.toolbar);
mTabLayout=findViewById(R.id.tabLayout);
mViewPager=findViewById(R.id.viewPager);
setSupportActionBar(mToolbar);
PagerAdpater adpater=new PagerAdpater(getSupportFragmentManager());
adpater.addFragment(new GreetingFragment(),"Greeting");
adpater.addFragment(new NumberFragment(),"Numbers");
adpater.addFragment(new EatingOutFragment(),"Eating Out");
adpater.addFragment(new ColorFragment(),"Colors");
adpater.addFragment(new ClothesFragment(),"Clothes");
adpater.addFragment(new FamilyFragment(),"Family");
mViewPager.setAdapter(adpater);
mTabLayout.setupWithViewPager(mViewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_search_menu,menu);
MenuItem menuItem=menu.findItem(R.id.action_search);
SearchView searchView=(SearchView) menuItem.getActionView();
searchView.setQueryHint("Type here to search");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
//Dont Know what to do now??
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
Здесь мой класс адаптера RecyclerView
import android.content.Context;
import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.fidu.learnchinese.R;
import com.fidu.learnchinese.models.ChineseLanguage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class RecyclerViewAdpater extends RecyclerView.Adapter<RecyclerViewAdpater.MyViewHolder> implements Filterable {
private List<ChineseLanguage> mChineseLanguages;
private List<ChineseLanguage> mChineseLanguagesFull;
private Context mContext;
private MediaPlayer mMediaPlayer;
public RecyclerViewAdpater(List<ChineseLanguage> chineseLanguages, Context context) {
mChineseLanguages = chineseLanguages;
mChineseLanguagesFull=new ArrayList<>(mChineseLanguages);
mContext = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
holder.txtEnglishWord.setText(mChineseLanguages.get(position).getEnglishAlphabet());
holder.txtChineseWord.setText(mChineseLanguages.get(position).getChineseAlphabet());
holder.txtPronunciation.setText(mChineseLanguages.get(position).getPronounciation());
holder.btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
releasaMedia();
mMediaPlayer=MediaPlayer.create(mContext,mChineseLanguages.get(position).getSound());
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
releasaMedia();
}
});
}
});
}
private void releasaMedia(){
if (mMediaPlayer!=null){
mMediaPlayer.release();
}
mMediaPlayer=null;
}
@Override
public int getItemCount() {
return mChineseLanguages.size();
}
@Override
public Filter getFilter() {
return filter;
}
private Filter filter=new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<ChineseLanguage> filteredList=new ArrayList<>();
if (constraint.toString().isEmpty()){
filteredList.addAll(mChineseLanguagesFull);
}else {
for(ChineseLanguage item: mChineseLanguagesFull){
if (item.getEnglishAlphabet().toLowerCase().contains(constraint.toString().toLowerCase().trim())){
filteredList.add(item);
}
}
}
FilterResults filterResults=new FilterResults();
filterResults.values=filteredList;
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mChineseLanguages.clear();
mChineseLanguages.addAll((Collection<? extends ChineseLanguage>) results.values);
notifyDataSetChanged();
}
};
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtEnglishWord,txtChineseWord,txtPronunciation;
ImageButton btnPlay;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
txtEnglishWord=itemView.findViewById(R.id.txtEnglishWord);
txtChineseWord=itemView.findViewById(R.id.txtChineseWord);
txtPronunciation=itemView.findViewById(R.id.txtPronunciation);
btnPlay=itemView.findViewById(R.id.btnPlay);
}
}
}
А вотФрагмент для лучшего понимания
public class ClothesFragment extends Fragment {
private RecyclerView mRecyclerViewClothes;
private List<ChineseLanguage> mClothes;
public ClothesFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mClothes=new ArrayList<>();
mClothes.add(new ChineseLanguage("Wear","穿","chuān",R.raw.clothes_wear));
mClothes.add(new ChineseLanguage("Put On","穿","chuān",R.raw.clothes_put_on));
mClothes.add(new ChineseLanguage("Take On","脱下","tuō xià",R.raw.clothes_take_off));
mClothes.add(new ChineseLanguage("Clothes","衣服","yī fú",R.raw.clothes_clothes));
mClothes.add(new ChineseLanguage("Trousers","裤子","kù zi",R.raw.clothes_trousers));
mClothes.add(new ChineseLanguage("Shirt","衬衫","chèn shān",R.raw.clothes_shirt));
mClothes.add(new ChineseLanguage("T-shirt","衬衣","chèn yī",R.raw.clothes_t_shirt));
mClothes.add(new ChineseLanguage("Dress","连衣裙","lián yī qún",R.raw.clothes_dress));
mClothes.add(new ChineseLanguage("Pair of Socks","袜子","wà zi",R.raw.clothes_pair_of_socks));
mClothes.add(new ChineseLanguage("Pair of Shoes","鞋子","xié zi",R.raw.clothes_pair_of_shoes));
mClothes.add(new ChineseLanguage("Sweatshirt","运动衫","yùn dòng shān",R.raw.clothes_sweatshirt));
mClothes.add(new ChineseLanguage("Jacket","夹克","jiá kè",R.raw.clothes_jacket));
mClothes.add(new ChineseLanguage("Skirt","裙子","qún zi",R.raw.clothes_skirt));
mClothes.add(new ChineseLanguage("Suit","套装","tào zhuāng",R.raw.clothes_suit));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_clothes, container, false);
mRecyclerViewClothes=view.findViewById(R.id.recyclerViewClothes);
mRecyclerViewClothes.setLayoutManager(new LinearLayoutManager(getContext()));
RecyclerViewAdpater adpater=new RecyclerViewAdpater(mClothes,getActivity());
mRecyclerViewClothes.setAdapter(adpater);
return view;
}
}
Теперь то, что я хочу, это. Когда я ввожу текст в строке поиска. Следует отфильтровать от всех фрагментов