используйте Редактировать текст для поиска в программе повторного просмотра внутри фрагмента - PullRequest
0 голосов
/ 03 февраля 2019

привет, пожалуйста, мне нужна помощь. Я хочу добавить Edittext, чтобы использовать ее для поиска recycleview

моя программа будет работать без сбоев, но она не будет работать в моем проекте. У меня есть BottomNavigation (fragment) и внутри него я использовал Tablayout (fragment) (fragment внутри другого fragment (вкладка в нижней части навигации)) edittext for using search inside recycler view and Tablayout and fragment У меня нет ошибок, номой поиск не работает ** Если это возможно для вас, пожалуйста, добавьте этот код в ваш новый пустой проект, протестируйте его и помогите мне **

Я использовал этот поиск в этом учебном проекте

https://codinginflow.com/tutorials/android/searchview-recyclerview

Мой основной код активности (Фрагмент BottomNavigation находится внутри MainActicity)

package forokans.sirwansoft.forlearn;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


    FrameLayout frameLayout;
    //call Fragments class
    private BottomNavigationFragment fragmentOne;
  /*  private FragmentTwo fragmentTwo;
    private FragmentThree fragmentThree;*/


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:

                    setFragment(fragmentOne);
                    return true;
                case R.id.navigation_dashboard:
/*
                    setFragment(fragmentTwo);
*/
                    return true;
                case R.id.navigation_notifications:
/*
                    setFragment(fragmentThree);
*/
                    return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        //make new from fragments
        //fragment of BottomNavigation
        fragmentOne = new BottomNavigationFragment();
     /*   fragmentThree = new FragmentThree();
        fragmentTwo = new FragmentTwo();
*/
        setFragment(fragmentOne);

        frameLayout = findViewById(R.id.main_fream);


    }

    private void setFragment(Fragment fragment) {

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.main_fream, fragment);
        fragmentTransaction.commit();

    }

}

My Layout Of main_activity.xml

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <FrameLayout
            android:id="@+id/main_fream"
            android:layout_width="match_parent"
            android:layout_height="match_parent">


        </FrameLayout>

        <android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="0dp"
            android:layout_marginEnd="0dp"
            android:background="?android:attr/windowBackground"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/navigation" />

    </android.support.constraint.ConstraintLayout>

Класс фрагмента «Моя нижняя навигация»

package forokans.sirwansoft.forlearn;


import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;


/**
 * A simple {@link Fragment} subclass.
 */
public class BottomNavigationFragment extends Fragment {

    TabLayout tabLayout;
    EditText search;
    ViewPager viewPager;

    public BottomNavigationFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_bottom_navigation, container, false);
        search=view.findViewById(R.id.searchinfragmentOne);
        tabLayout=view.findViewById(R.id.tablayout_id);
        viewPager=view.findViewById(R.id.viewpager);


        ViewPagerAdapterForTabs adapter = new ViewPagerAdapterForTabs(getChildFragmentManager());
        // this is Tab Fragments
        adapter.AddFragment(new TabFragment(),"Tab1");

        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        return view;

    }

}

** и «Моя компоновка этой навигационной кнопки» **

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".BottomNavigationFragment">

    <EditText
        android:id="@+id/searchinfragmentOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:hint="search ..." />

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/colorPrimary"
        app:tabMode="scrollable"
        app:tabTextColor="@color/colorPrimaryDark" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v4.view.ViewPager>

</LinearLayout>

Фрагмент вкладки

package forokans.sirwansoft.forlearn;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class TabFragment extends Fragment {

    public List<Items> lstItems;
    public RecyclerViewAdapter mAdapter;
    EditText search;

    public TabFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_tab, container, false);

        lstItems = new ArrayList<>();
        lstItems.add(new Items("a", "11265", "27500", "horizental", R.drawable.gemtv));
        lstItems.add(new Items("b", "11265", "27500", "horizental", R.drawable.bbc));
        lstItems.add(new Items("c", "11265", "27500", "horizental", R.drawable.voa));
        lstItems.add(new Items("d", "11265", "27500", "horizental", R.drawable.manoto));


        search = view.findViewById(R.id.searchintabbadrkurdi);
        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                filter(s.toString());

            }
        });

        RecyclerView myrv = view.findViewById(R.id.recyclerview_id_badr_kurdi);
        RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(getContext(), lstItems);
        myrv.setLayoutManager(new GridLayoutManager(getContext(), 3));
        myrv.setAdapter(mAdapter);



        /*mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new RecyclerViewAdapter(mExampleList);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);*/
        return view;
    }

    private void filter(String text) {
        ArrayList<Items> filteredList = new ArrayList<>();

        for (Items item : lstItems) {
            if (item.getTvName().toLowerCase().contains(text.toLowerCase())) {
                filteredList.add(item);
            }
        }

        mAdapter.filterList(filteredList);
    }
}

Расположение вкладок.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TabFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <EditText
            android:id="@+id/searchintabbadrkurdi"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerview_id_badr_kurdi"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </android.support.v7.widget.RecyclerView>
    </LinearLayout>

</FrameLayout>

Класс My Item

package forokans.sirwansoft.forlearn;

public class Items {
    private String TvName;
    private String Forekans;
    private String BistoHaft;
    private String Horizental;
    private int ImageSrc;

    //main constructor
    public Items() {
    }

    // constructor
    public Items(String tvName, String forekans, String bistoHaft, String horizental, int imageSrc) {
        TvName = tvName;
        Forekans = forekans;
        BistoHaft = bistoHaft;
        Horizental = horizental;
        ImageSrc = imageSrc;
    }

    //getter
    public String getTvName() {
        return TvName;
    }
    //getter

    public String getForekans() {
        return Forekans;
    }

    public String getBistoHaft() {
        return BistoHaft;
    }
    //getter

    public int getImageSrc() {
        return ImageSrc;
    }

    public String getHorizental() {
        return Horizental;
    }
}

My Adapter View Adapter Class

package forokans.sirwansoft.forlearn;

import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
    private Context mContext;
    private List<Items> lstItems;

    public RecyclerViewAdapter(Context mContext, List<Items> lstItems) {
        this.mContext = mContext;
        this.lstItems = lstItems;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view;
        LayoutInflater mInflater = LayoutInflater.from(mContext);
        view = mInflater.inflate(R.layout.recycler_view_item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {

        //in main activity displays
        holder.tv_Items_TvName.setText(lstItems.get(position).getTvName());
        holder.tv_Items_cat.setText(lstItems.get(position).getForekans());
        holder.tv_Items_desc.setText(lstItems.get(position).getBistoHaft());
        holder.tv_Items_horizental.setText(lstItems.get(position).getHorizental());
        holder.img_Items_ImageSrc.setImageResource(lstItems.get(position).getImageSrc());
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
            }
        });


    }

    @Override
    public int getItemCount() {
        return lstItems.size();
    }

    public void filterList(ArrayList<Items> filteredList) {
        lstItems = filteredList;
        notifyDataSetChanged();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView tv_Items_TvName;
        TextView tv_Items_cat;
        TextView tv_Items_desc;
        TextView tv_Items_horizental;
        ImageView img_Items_ImageSrc;
        CardView cardView;

        public MyViewHolder(View itemView) {
            super(itemView);

            tv_Items_TvName = itemView.findViewById(R.id.Items_TvName_id);
            tv_Items_cat = itemView.findViewById(R.id.Items_cat_id);
            tv_Items_desc = itemView.findViewById(R.id.Items_desc_id);
            tv_Items_horizental = itemView.findViewById(R.id.Items_Hor_id);
            img_Items_ImageSrc = itemView.findViewById(R.id.Items_img_id);
            cardView = itemView.findViewById(R.id.cardview_id);


        }
    }

}

и класс My ViewPagerAdapter для вкладок

package forokans.sirwansoft.forlearn;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdapterForTabs extends FragmentPagerAdapter {

    private final List<Fragment> FragmentList = new ArrayList<>();
    private final List<String> FragmentListTitles = new ArrayList<>();

    public ViewPagerAdapterForTabs(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return FragmentList.get(position);
    }

    @Override
    public int getCount() {
        return FragmentListTitles.size();
    }

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


    }
    public void AddFragment(Fragment fragment, String titles) {
        FragmentList.add(fragment);
        FragmentListTitles.add(titles);
    }
}

1 Ответ

0 голосов
/ 03 февраля 2019

я обнаружил, измените это

  RecyclerView myrv = view.findViewById(R.id.recyclerview_id_badr_kurdi);
        RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(getContext(), lstItems);
        myrv.setLayoutManager(new GridLayoutManager(getContext(), 3));
        myrv.setAdapter(mAdapter);

на это

  RecyclerView myrv = view.findViewById(R.id.recyclerview_id_badr_kurdi);
       mAdapter = new RecyclerViewAdapter(getContext(), lstItems);
        myrv.setLayoutManager(new GridLayoutManager(getContext(), 3));
        myrv.setAdapter(mAdapter);

причина , прежде чем мы вызовем onCreate этого RecyclerViewAdapter mAdapter = new RecyclerViewAdapter (getContext (), lstItems);был инициализирован и в последнем случае, если мы сделаем этот класс новым объектом, это будет новое значение инициализации

...