获取更新的RecyclerView.Adapter

时间:2017-01-10 09:06:30

标签: android android-fragments android-recyclerview recycler-adapter

在以下活动中,每当我对Switch执行检查操作时,它都会过滤列表( originallist )。

在检查/点击交换机之前,我从RecyclerView过滤了fragment列表,更新了适配器,并在片段交易后过滤了列表。

但是当我检查Switch时,过滤器操作是在原始列表上执行的,而不是片段事务后我应该得到的过滤列表。

如何在活动中获取更新的RecyclerView.Adapter

public class TransactionsActivity extends AppCompatActivity implements ActivityCommunicator {

    SearchView searchtrans;
    SearchView searchView;
    private RecyclerView recyclerView;
    private Button monthButton, filterButton;
    public static RecentTransAdapter mAdapter;
    private Switch aSwitch;
    boolean filtered;
    public FragmentCommunicator fragmentCommunicator;
    String dateSelected;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transactions);
/*
        Slide slide = new Slide(Gravity.TOP);
        slide.addTarget(R.id.trans);
        getWindow().setEnterTransition(slide);
*/
        searchtrans = (SearchView) findViewById(R.id.searchTrans);

        searchtrans.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;
            }
        });
        recyclerView = (RecyclerView) findViewById(R.id.trans);
        List<Transaction> newList = new ArrayList<Transaction>();
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        newList = Transaction.transactionList;

        monthButton = (Button) findViewById(R.id.monthButton);
        // filterButton = (Button) findViewById(R.id.filterButton);
        aSwitch = (Switch) findViewById(R.id.switch1);

        String currentMonth = "";

        Calendar cal = Calendar.getInstance();
      /*  Date date = new Date();
        cal.setTime(date);
*/
        currentMonth = new SimpleDateFormat("MMMM").format(cal.getTime());

        monthButton.setText(currentMonth);

        monthButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FragmentManager fm = getSupportFragmentManager();
                // FragmentTransaction ft = fm.beginTransaction();
                MyFrag dFragment = new MyFrag();
                // Show DialogFragment
                dFragment.show(fm, "Dialog Fragment");
//                fragmentCommunicator.passDataToFragment(mAdapter);
            }
        });

        mAdapter = new RecentTransAdapter(newList, this);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                Log.d("list is ",String.valueOf(mAdapter.getItemCount()));

                if (!isChecked) {
                    Log.d("notchecked","yo");
                    mAdapter.getFilter().filter("");

                } else {
                        mAdapter.getFilter().filter("credit");
                }
                recyclerView.setAdapter(mAdapter);
            }
        });
        //  RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        //  recyclerView.setLayoutManager(mLayoutManager);
        //recyclerView.setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    public void passDataToActivity(String someValue, RecentTransAdapter recentTransAdapter) {
        dateSelected = someValue;
        //dateSelected = "someTest";
        monthButton.setText(dateSelected);
        mAdapter = recentTransAdapter;
    }

}

适配器:

public class RecentTransAdapter extends RecyclerView.Adapter<RecentTransAdapter.MyViewHolder> implements Filterable{

    private LayoutInflater inflater;
    List<Transaction> transactionList ;
    List<Transaction> filteredTransList;


    public RecentTransAdapter(List<Transaction> transactionList,Context context){
        this.transactionList = transactionList;
        filteredTransList = transactionList;
        inflater = LayoutInflater.from(context);

    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.transaction, parent, false);
        MyViewHolder myViewHolder = new MyViewHolder(itemView);
        return myViewHolder;
    }

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

        Transaction transaction = filteredTransList.get(position);

        holder.tamt.setText(transaction.amount);
        if(transaction.type.toLowerCase().contains("credit"))
        {
            holder.tamt.setTextColor(Color.parseColor("#009f00"));
            holder.tamt.setText("(+) "+transaction.amount);
        }
        else
        {
            holder.tamt.setTextColor(Color.parseColor("#9f0000"));
            holder.tamt.setText("(-) "+transaction.amount);
        }
        Date date = null;
        String formattedTime=null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            SimpleDateFormat output = new SimpleDateFormat("dd MMM yy");
            Date d = sdf.parse(transaction.date);
             formattedTime = output.format(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        holder.tdate.setText(formattedTime.toString());
        holder.tdesc.setText(transaction.desc);

        if(holder.tdesc.getText().toString().contains("BOB E-Banking"))
        {
            //holder.imageView.setImageBitmap(getBitmapFromURL(""));
            holder.imageView.setImageResource(R.drawable.bob);
        }
        else if(holder.tdesc.getText().toString().toLowerCase().contains("paytm"))
        {
            Glide.with(getApplicationContext())
                    .load("http://www.irctcstationcode.com/wp-content/uploads/2015/11/Paytm-Wallet.jpg")
                    .asBitmap()
                    .into(holder.imageView);

        }
    }

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

    @Override
    public Filter getFilter() {
        return new MyFilter(this,transactionList);
    }

    public void setList(List<Transaction> list) {
        this.filteredTransList = list;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        public TextView tdate , tdesc , tamt ;
        public ImageView imageView ;
        public MyViewHolder(View view) {
            super(view);

            imageView = (ImageView)view.findViewById(R.id.timg);

            tdate = (TextView)view.findViewById(R.id.tdate);

            tdesc = (TextView)view.findViewById(R.id.tdesc);

            tamt = (TextView)view.findViewById(R.id.tamt);
        }

    }

过滤:

class MyFilter extends Filter {

    private final RecentTransAdapter adapter;

    private final List<Transaction> originalList;

    private final List<Transaction> filteredList;

    public MyFilter(RecentTransAdapter adapter, List<Transaction> originalList) {
        super();
        this.adapter = adapter;
        this.originalList = originalList;
        this.filteredList = new ArrayList<>();
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        filteredList.clear();
        final FilterResults results = new FilterResults();

        Log.d("constrianss iss", constraint.toString());

        String constring = constraint.toString();

        if (constraint.length() == 0) {

            filteredList.addAll(originalList);
            Log.d("filteredLen", String.valueOf(filteredList.size()));
        } else if (constring.equals("credit")) {
            final String filterPattern = constraint.toString().toLowerCase().trim();

            for (final Transaction tr : originalList) {

                if (filterPattern.equals("credit") && tr.type.toLowerCase().contains("credit")) {
                    Log.d("FilterSucc", tr.desc + " : " + tr.date);
                    filteredList.add(tr);
                }
            }
        } else if (constraint.toString().trim().toLowerCase().matches("[a-z]{3}[-][0-9]{2}")) {
            StringBuilder sb = new StringBuilder("");
            sb.append("11-").append(constring);

            for (final Transaction tr : originalList) {

                Date date = null;
                try {
                    date = new SimpleDateFormat("dd-MMM-yy").parse(sb.toString());
                    Log.d("dubug2", date.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);

                int month = cal.get(Calendar.MONTH) + 1;
                int year = cal.get(Calendar.YEAR);
                String monthStr = null;
                monthStr = String.valueOf(month);
                if (String.valueOf(month).length() == 1) {
                    monthStr = "0" + month;
                }

               if (tr.date.trim().startsWith("" + year + "-" + monthStr)) {
                    filteredList.add(tr);
                    //  TransactionsActivity.mAdapter.setList(filteredList);
                }


            }
        } else {
            for (final Transaction tr : originalList) {
                if (tr.desc.toLowerCase().contains(constraint.toString())) {
                    filteredList.add(tr);
                }
            }
        }
        results.values = filteredList;
        results.count = filteredList.size();
        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        // adapter.filteredTransList.clear();
        adapter.setList(filteredList);
        adapter.notifyDataSetChanged();
        TransactionsActivity.mAdapter=adapter;
    }
}

1 个答案:

答案 0 :(得分:0)

检查后将适配器换成:

recyclerView.swapAdapter(new RecentTransAdapter(filteredList), false);