В следующем действии, когда я выполняю действие проверки на Switch
, он фильтрует список (originallist).Получение обновления RecyclerView.Adapter
Перед тем, как проверить/щелкнуть переключатель, я фильтрую список RecyclerView
с fragment
, адаптер обновляется, и список фильтруется после транзакции фрагмента.
Но тогда, когда я проверяю переключатель, операция фильтра выполняется в исходном списке, а не в списке фильтров, который я должен получить после транзакции фрагмента.
Как получить обновленный 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;
}
}
опубликовать ваш класс адаптера, а –
да я обновил – user3820753