使用回收站视图在片段中搜索功能

时间:2018-02-13 11:08:18

标签: android

以下是我的代码

package com.mypoolin.hybrid_upi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
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 android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.builder.Builders;
import com.mypoolin.hybrid_upi.objects.Banks;
import com.mypoolin.mypoolinsupportlibrary.util.Log;

import java.util.ArrayList;


//import com.bumptech.glide.Glide;

public class ListFragment extends Fragment {
    private static final String TAG = "BankListFragment";
    public static boolean networkFailure = false;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    // ArrayList<HashMap<String, String>> bankData = new ArrayList<>();
    ArrayList<Banks> bankData = new ArrayList<>();
    ArrayList<Banks> bankDataOriginl = new ArrayList<>();
    RecyclerView recyclerViewBankList;
    EditText searchText;
    ImageButton imageButtonClearSearch;
    SwipeRefreshLayout swipeRefreshLayoutBank;
    String transactionType = "T";
    // TODO: Rename and change types of parameters
    int confirmed = 0;
    int upi = 0;
    int forWalletRedeem = 0;
    private OnFragmentInteractionListener mListener;
    private RecyclerView.Adapter mAdapter;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment BankListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BankListFragment newInstance(ArrayList<Banks> param1, String transactionType) {
        BankListFragment fragment = new BankListFragment();
        Bundle args = new Bundle();
        args.putSerializable("bankList", param1);
        args.putString("transactionType", transactionType);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            if (getArguments().containsKey("bankList")) {
                bankDataOriginl = (ArrayList<Banks>) getArguments().getSerializable("bankList");
                bankData = (ArrayList<Banks>) getArguments().getSerializable("bankList");
            }
            if (getArguments().containsKey("transactionType")) {
                transactionType = getArguments().getString("transactionType");
            }
        }
        //  MyPoolinUtil.hideSoftInput(getActivity());

    }

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

    }

    private void loadView(View view, ArrayList<Banks>list) {
        Log.d(TAG,"test list:"+list);
        searchText = (EditText) view.findViewById(R.id.searchEditText);
        imageButtonClearSearch = (ImageButton) view.findViewById(R.id.imageButtonClearSearch);
        imageButtonClearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchText.setText("");
            }
        });

        swipeRefreshLayoutBank = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout_bank_list);
        recyclerViewBankList = (RecyclerView) view.findViewById(R.id.bankListRecyclerView);
        //recyclerViewBankList.addItemDecoration(new DividerItemDecoration(getActivity().getApplicationContext(), DividerItemDecoration.VERTICAL_LIST));
        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        recyclerViewBankList.setHasFixedSize(true);
        // use a linear layout manager
        recyclerViewBankList.setLayoutManager(new LinearLayoutManager(getActivity()));
        // create an Object for Adapter
        mAdapter = new BankDataAdapter(getActivity().getApplicationContext(), bankData);
        // set the adapter object to the Recyclerview
        recyclerViewBankList.setAdapter(mAdapter);
        //recyclerViewBankList.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        try {
            searchText.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) {
                    if (s.toString().isEmpty()) {
                        imageButtonClearSearch.setVisibility(View.GONE);
                    } else {
                        imageButtonClearSearch.setVisibility(View.VISIBLE);
                    }
                    String name = s.toString();
                    Log.e(this.getClass().getName(), name);
                    swapList(name);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void swapList(String name) {
        ArrayList<Banks> newList = new ArrayList<Banks>();
        if (name.trim().isEmpty()) {
            //this.contactList=contactListoriginal;
            mAdapter = new BankDataAdapter(getActivity().getApplicationContext(), bankDataOriginl);
            // set the adapter object to the Recyclerview
            recyclerViewBankList.setAdapter(mAdapter);
        } else {
            mAdapter = new BankDataAdapter(getActivity().getApplicationContext(), bankData);
            for (Banks c : bankData) {
                if (containsName(name, c.getBankName())) {
                    newList.add(c);
                }
            }
            mAdapter = new BankDataAdapter(getActivity().getApplicationContext(), newList);
            recyclerViewBankList.setAdapter(mAdapter);
            mAdapter.notifyDataSetChanged();
        }
    }

    public boolean containsName(String s, String name) {
        if (s != null && name != null) {
            int l = s.length();
            if (name.length() >= l && name.substring(0, l).equalsIgnoreCase(s)) {
                return true;
            }
            else {
                String[] names = name.split("[\\s]+");
                for (String n : names) {
                    if (n.length() >= l && n.substring(0, l).equalsIgnoreCase(s))
                        return true;
                }
            }
        }
        return false;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
       /* if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }*/
    }

    @Override
    public void onDetach() {
        super.onDetach();
     /*   mListener = null;*/
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private class BankDataAdapter extends RecyclerView.Adapter<BankDataAdapter.ViewHolder> {
        Context context;

        private ArrayList<Banks> bankList;

        public BankDataAdapter(Context context, ArrayList<Banks> contactList) {
            this.bankList = contactList;
            this.context = context;
            //ImageLoader imageLoader = ImageLoader.getInstance();

        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_row_bank_list, null);

            // create ViewHolder

            ViewHolder viewHolder = new ViewHolder(itemLayoutView);

            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            final int pos = position;
            viewHolder.textViewBankName.setText(bankList.get(pos).getBankName());
            //  viewHolder.imageViewBankLogo.setImageURI(Uri.parse("http://hybridsdk.mypoolin.com/get_bank_image/" + bankList.get(pos).getBankCode()));
            /*Glide.with(context)
                    .load("http://hybridsdk.mypoolin.com/get_bank_image/"+bankList.get(pos).getBankCode())
                    .asBitmap()
                    //.error(MyPoolinUtil.getDrawableFromText(position, bankList.get(position).getBankName(), context))
                    .into(viewHolder.imageViewBankLogo);*/

            Ion.with(viewHolder.imageViewBankLogo)
                    //.error(MyPoolinUtil.getDrawableFromText(position, bankList.get(position).getBankName(), context))
                    .load("http://mypoolin.com/hybrid_upi/get_bank_image/" + bankList.get(pos).getBankCode());
        }

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

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {


            public TextView textViewBankName;
            public ImageView imageViewBankLogo;

            public ViewHolder(View itemLayoutView) {
                super(itemLayoutView);
                imageViewBankLogo = (ImageView) itemLayoutView.findViewById(R.id.imageViewBankLogo);
                textViewBankName = (TextView) itemLayoutView.findViewById(R.id.textViewBankName);
                itemLayoutView.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                int position = getAdapterPosition(); // gets item position
                if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it
                    Banks user = bankList.get(position);
                    // We can access the data within the views
                    //  Toast.makeText(context, bankList.get(position).getBankName() + s, Toast.LENGTH_SHORT).show();
                    Intent returnIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("bankName", bankList.get(position).getBankName());
                    bundle.putString("bankCode", bankList.get(position).getBankCode());
                    bundle.putString("transactionType", transactionType);

                    returnIntent.putExtras(bundle);
                    getActivity().setResult(Activity.RESULT_OK, returnIntent);
                    getActivity().finish();

                }
            }
        }
    }

}

我在片段的onCreate方法中从getExtra获取了银行列表数据,我将银行列表数据保存为Arraylist作为bankdata和bankoriginaldata,我的问题是我无法在swaplist方法中获取银行列表数据,并且搜索功能无效。在foreach循环库数据变为null之前的交换列表方法中,但是我在加载视图方法中有银行数据,但在交换列表中没有。任何人都可以告诉我们发生了什么吗? 如何解决上述问题?我想知道为什么银行数据在交换方法中变为空以及如何访问它。 我案例中的搜索功能是否会按预期工作?

1 个答案:

答案 0 :(得分:0)

  private void swapList(String name) {
        bankData.clear();
        if (name.trim().isEmpty()) {
            bankData.addAll(bankDataOriginl);
        } else {
            for (Banks c : bankDataOriginl) {
                if (containsName(name, c.getBankName())) {
                    bankData.add(c);
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

更改你的swapList方法。

在你的oncreate方法中再改变一件事

if (getArguments() != null) {
            if (getArguments().containsKey("bankList")) {
                bankDataOriginl = (ArrayList<Banks>) getArguments().getSerializable("bankList");
            }
            if (getArguments().containsKey("transactionType")) {
                transactionType = getArguments().getString("transactionType");
            }
        }

从loadView调用swapList(“”)。