Страницы

Поиск по вопросам

среда, 17 июля 2019 г.

Android. RecyclerView поиск по элементам

Использую RecyclerView для отображения списка с элементами. Хочу реализовать поиск по этому способу, желательно наиболее простым и действенным способом. Не смог разобраться в тех примерах что нашел в интернете, т.к. сложны для меня (я пока что новичок). Элемент списка:



RecyclerViewAdapter:
package com.starikov.definitions.adapters;
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView;
import com.starikov.definitions.MainActivity; import com.starikov.definitions.R;
public class RecyclerViewAdapter extends RecyclerView.Adapter{
private int[] textId;
public static class ViewHolder extends RecyclerView.ViewHolder{ private LinearLayout mLinearLayout; public ViewHolder(LinearLayout v){ super(v); mLinearLayout = v; } }
public RecyclerViewAdapter(int[] textId){ this.textId = textId; }
@Override public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LinearLayout cv = (LinearLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.definition, parent, false); return new ViewHolder(cv); }
@Override public void onBindViewHolder(ViewHolder holder, int position) { float textSize; LinearLayout linearLayout = holder.mLinearLayout; TextView textView = linearLayout.findViewById(R.id.textId); textSize = MainActivity.sharedPreferences.getFloat(MainActivity.APP_PREFERENCES_TEXT_SIZE, 15); textView.setTextSize(textSize); textView.setText(linearLayout.getResources().getText(textId[position])); }
@Override public int getItemCount() { return textId.length; } }
Фрагмент со списком RecyclerView
package com.starikov.definitions;
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;
import com.starikov.definitions.adapters.RecyclerViewAdapter; import com.starikov.definitions.definitions.Geometry;
public class GeometryDefinitionFragment extends Fragment {
private static int themePosition; private int[] definitionTexts; int formulaId = 0;
public static void setChoosedTheme(int position){ themePosition = position; }
@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { RecyclerView formulaRecycler = (RecyclerView) inflater.inflate(R.layout.himical_definition_fragment, container, false);
switch (themePosition){ case 0: definitionTexts = new int[Geometry.ugli.length]; for (int i = 0; i < Geometry.ugli.length; ++i) { definitionTexts[formulaId] = Geometry.ugli[i].getTextId(); formulaId++; } getActivity().setTitle("Углы"); break; case 1: definitionTexts = new int[Geometry.parallenie_pryamie.length]; for (int i = 0; i < Geometry.parallenie_pryamie.length; ++i) { definitionTexts[formulaId] = Geometry.parallenie_pryamie[i].getTextId(); formulaId++; } getActivity().setTitle("Параллельные прямые"); break; case 2: definitionTexts = new int[Geometry.treugolniki.length]; for (int i = 0; i < Geometry.treugolniki.length; ++i) { definitionTexts[formulaId] = Geometry.treugolniki[i].getTextId(); formulaId++; } getActivity().setTitle("Треугольники"); break; case 3: definitionTexts = new int[Geometry.pryamoygolnii_treugolnik.length]; for (int i = 0; i < Geometry.pryamoygolnii_treugolnik.length; ++i) { definitionTexts[formulaId] = Geometry.pryamoygolnii_treugolnik[i].getTextId(); formulaId++; } getActivity().setTitle("Прямоугольный треугольник"); break; case 4: definitionTexts = new int[Geometry.gmt.length]; for (int i = 0; i < Geometry.gmt.length; ++i) { definitionTexts[formulaId] = Geometry.gmt[i].getTextId(); formulaId++; } getActivity().setTitle("Геометрические места точек"); break; case 5: definitionTexts = new int[Geometry.gomotetia.length]; for (int i = 0; i < Geometry.gomotetia.length; ++i) { definitionTexts[formulaId] = Geometry.gomotetia[i].getTextId(); formulaId++; } getActivity().setTitle("Геометрические места точек"); break; case 6: definitionTexts = new int[Geometry.chetirehugolnik.length]; for (int i = 0; i < Geometry.chetirehugolnik.length; ++i) { definitionTexts[formulaId] = Geometry.chetirehugolnik[i].getTextId(); formulaId++; } getActivity().setTitle("Четырехугольники"); break; }
RecyclerViewAdapter adapter = new RecyclerViewAdapter(definitionTexts); formulaRecycler.setAdapter(adapter); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); formulaRecycler.setLayoutManager(layoutManager); return formulaRecycler; }

@Override public void onResume() { super.onResume(); MainActivity.lastOpenedFragment = new GeometryDefinitionFragment(); MainActivity.genometryDefinitionFrag = true; }
@Override public void onPause() { super.onPause(); MainActivity.genometryDefinitionFrag = false; } }
В нем я получаю id с предыдущего фрагмента и для каждого id заполняю список разными элемнтами.
Класс Geometry
package com.starikov.definitions.definitions;
import com.starikov.definitions.R;
public class Geometry { private int textId;
public static final Geometry[] ugli = { new Geometry(R.string.ugol), new Geometry(R.string.razvernutii_ugol), new Geometry(R.string.pryamim_uglom), new Geometry(R.string.ostrim), new Geometry(R.string.tupim), new Geometry(R.string.smejnie), new Geometry(R.string.gradus), new Geometry(R.string.ravnimi), new Geometry(R.string.bissektrisa), new Geometry(R.string.vertical), new Geometry(R.string.uglom_mejdu_dvumya_peresekauch_praymamim), new Geometry(R.string.perpendikular), };
public static final Geometry[] parallenie_pryamie = { new Geometry(R.string.parallelnie_pryamie), new Geometry(R.string.teorema_suh_paral_pryamih), new Geometry(R.string.aksioma_paral_pryamih), new Geometry(R.string.sledstvie), new Geometry(R.string.parallelnie_pryamie_ugli), new Geometry(R.string.priznaki_parallelnosti_dvuh_prymih), new Geometry(R.string.svoistva_uglov_paral_pr), new Geometry(R.string.teorema_faleca), new Geometry(R.string.rashrir_faleca), };
public static final Geometry[] treugolniki = { new Geometry(R.string.treugolnik), new Geometry(R.string.uglom_treugolnika), new Geometry(R.string.vidi_treugolnikov), new Geometry(R.string.perimetr), new Geometry(R.string.sootnoshenie_ejdu_storonami_i_uglami_treugolnika), new Geometry(R.string.vneshnim), new Geometry(R.string.ravnimi__), new Geometry(R.string.priznaki_ravenstva_treugolnikov), new Geometry(R.string.srednyaya_linia), new Geometry(R.string.mediana), new Geometry(R.string.bissektrisa__), new Geometry(R.string.visota), new Geometry(R.string.svoistvo_srednei_linii_treugolnika), new Geometry(R.string.bissektrisa_ravnobedr), new Geometry(R.string.chetire_zamechatelnie_tochki_treugolnika), new Geometry(R.string.svoistva_median_treugolnika), new Geometry(R.string.reshit_treugolnik), };
public static final Geometry[] pryamoygolnii_treugolnik = { new Geometry(R.string.pryamougolnii_treugolnik), new Geometry(R.string.gipotenuza), new Geometry(R.string.kateti), new Geometry(R.string.swoistvo_mediani_provedennoi_na_gipotenuzu), new Geometry(R.string.priznaki_ravenstva_pryamougolnih_treugolnikov), new Geometry(R.string.v_pryamougolnom_treugolnike), new Geometry(R.string.teorema_pifagora), new Geometry(R.string.obratnaya_teorema_pifagora), new Geometry(R.string.teorema_kosinusov), new Geometry(R.string.teorema_sinusov), };
public static final Geometry[] gmt = { new Geometry(R.string.gmt), new Geometry(R.string.okrujnost), new Geometry(R.string.seredinnii_perpendikular), new Geometry(R.string.sovokupnost_dvuh_pryamih_parallelnoih_dannoi), new Geometry(R.string.parallelnaya_im_pruyamaya), new Geometry(R.string.sovokupnost_dvuh_pryamih), new Geometry(R.string.sovokupnost_dvuh_segmentov_bez_ih_konsov), };
public static final Geometry[] gomotetia = { new Geometry(R.string.gomotetia), new Geometry(R.string.preobrazovanie_podobia), new Geometry(R.string.podobnimi), new Geometry(R.string.sushestvovanie_podobnih_treugolnikov), new Geometry(R.string.svoistvo_preobrazovania_podobia), new Geometry(R.string.priznaki_podobia_treugolnikov), new Geometry(R.string.v_podobnih_treugolnikah), };
public static final Geometry[] chetirehugolnik = { new Geometry(R.string.chetirehugolnik), new Geometry(R.string.vershini_i_storoni), new Geometry(R.string.sosednie_protivoleshahie), new Geometry(R.string.sosednie_smejnie), new Geometry(R.string.diagonal), new Geometry(R.string.vipuklim), new Geometry(R.string.uglom), new Geometry(R.string.sosednie_protivoleshahie_ugli), new Geometry(R.string.svoistvo_uglov_vipuklogo_chetirehugolnika), new Geometry(R.string.perimetr___), new Geometry(R.string.svoistva_parallelograma), new Geometry(R.string.priznaki_parallelograma), new Geometry(R.string.pryamougolnik), new Geometry(R.string.svoistva_pryamougolnika), new Geometry(R.string.priaznaki_pryamougolnika), new Geometry(R.string.romb), new Geometry(R.string.svoistva_romba), new Geometry(R.string.prizanki_romba), new Geometry(R.string.kvadrat), new Geometry(R.string.svoistva_kvadrata), new Geometry(R.string.prizmnaki_kvadrata), new Geometry(R.string.eche_dva_prianaka_kvadrata), new Geometry(R.string.trapecia), new Geometry(R.string.osnovanie_trapecii), new Geometry(R.string.srednyaya_linia_trapecii), new Geometry(R.string.diagonal_trapecii), new Geometry(R.string.visota_trapecii), new Geometry(R.string.svoistva_trapecii), new Geometry(R.string.ravnobokoi_rapeciei), new Geometry(R.string.pryamougolnoi_trapeciei), new Geometry(R.string.svoistva_ravnobokoi_trapecii), };
private Geometry(int textId){ this.textId = textId; }
public int getTextId(){ return textId; } }
Прошу помощи, т.к. сам не разобрался.


Ответ

Разобрался, сделал:
activity_main.xml Тут макет для RecyclerView

android:scrollbarThumbVertical="@drawable/scrollview_thumb" и android:scrollbarTrackVertical="@drawable/vertical_scrollview_track" мои собственные макеты для полосы прокрутки (можно убрать, можно заменить своими)
MainActivity
package com.starikov.search;
import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuItem;
import java.util.ArrayList; import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView; private ArrayList mArrayList = new ArrayList(Formula.physicalFormuls.length); private RecyclerViewAdapter mAdapter;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.formula_recycler); mRecyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(layoutManager); mArrayList = setArray(mArrayList); // Заполняем список mAdapter = new RecyclerViewAdapter(mArrayList); // Создаем адаптер mRecyclerView.setAdapter(mAdapter); // Подключаем адаптер }
@Override public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem search = menu.findItem(R.id.search); // Подключаем SearchView SearchView searchView = (SearchView) MenuItemCompat.getActionView(search); search(searchView); return true; }
@Override public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item); }
private void search(SearchView searchView) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { mAdapter.getFilter().filter(query); return false; }
@Override public boolean onQueryTextChange(String newText) { mAdapter.getFilter().filter(newText); return true; } }); }
private ArrayList setArray(ArrayList list) { // Заполняю ArrayList готовым списком из класса Formula list.addAll(Arrays.asList(Formula.physicalFormuls)); return list; } }
main_menu.xml


Formula.java
package com.starikov.search;
public class Formula { private String name; private int imageId;
public Formula(String name, int imageId){ this.name = name; this.imageId = imageId; }

public static final Formula[] physicalFormuls = { // Текст по которому будет вестись поиск, и картинка которую ищем new Formula("закон движения", R.drawable.formul_zakon_dvijenia), new Formula("координатные уравнения движения", R.drawable.formul_koordinatnie_uravneniya_dvigenia), new Formula("перемещение точки тела",R.drawable.formul_peremechenie), .... };
public String getName(){ return name; }
public int getImageId(){ return imageId; }
public String toString() { return this.name; } }
card_view.xml (макет для элемента списка)





RecyclerViewAdapter.java
package com.starikov.search;
import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter implements Filterable{
private ArrayList mArrayList = new ArrayList<>(); private ArrayList mFilteredList = new ArrayList<>();
@Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence charSequence) { String charString = charSequence.toString();
if (charString.isEmpty()) { mFilteredList = mArrayList; } else { ArrayList filteredList = new ArrayList<>(); for (Formula formula : mArrayList) { if (formula.getName().toLowerCase().contains(charString)) { // Сортируем по тексту из Formula filteredList.add(formula); } } mFilteredList = filteredList; }
FilterResults filterResults = new FilterResults(); filterResults.values = mFilteredList; return filterResults; }
@Override protected void publishResults(CharSequence charSequence, FilterResults filterResults) { mFilteredList = (ArrayList) filterResults.values; notifyDataSetChanged(); } }; }
public static class ViewHolder extends RecyclerView.ViewHolder{ private CardView mCardView; private ImageView imageView; public ViewHolder(CardView v){ super(v); mCardView = v; imageView = v.findViewById(R.id.info_image); } }
public RecyclerViewAdapter(ArrayList arrayList){ mArrayList = arrayList; mFilteredList = arrayList; }
@Override public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false); return new ViewHolder(cv); }
@Override public void onBindViewHolder(ViewHolder holder, int position) { holder.imageView.setImageDrawable(holder.mCardView.getResources().getDrawable(mFilteredList.get(position).getImageId())); holder.imageView.setContentDescription(mFilteredList.get(position).getName()); }
@Override public int getItemCount() { return mFilteredList.size(); } }
в Gradle зависимости для CardView и RecyclerView
compile 'com.android.support:recyclerview-v7:26.1.0' implementation 'com.android.support:cardview-v7:26.1.0'
Буду рад советам как улучшить код!

Комментариев нет:

Отправить комментарий