使用适配器选择微调项目

时间:2018-03-07 04:47:39

标签: android

我创建了一个actvity并有三个标签。在第三个标签中,有一个spinner。我列出了从PAYMENTS致电EXPENSE的两个列表APIcardviews。最初这两个列表将显示混合。 spinner包含“ALL"PAYMENTEXPENSE。每当我选择ALL时,通常list默认listPAYMENT选项应仅显示付款list,费用应仅显示费用。

屏幕截图

enter image description here

    //My whole class






   public class Approvals extends AppCompatActivity {

      static TextView startDate,endDate;
        private SectionsPagerAdapter mSectionsPagerAdapter;

        private ViewPager mViewPager;

        static ArrayList<AsyncTask> asyncTasks=new ArrayList<>();
        final static String ALL="All",PAYMENTS="Payments",EXPENSES="Expenses";
        String[] Pay = { "Payment", "Expense" };

        static CustomAdapter aadapter;
        static CustomAdapter padapter;
        static CustomAdapter eadapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_approvals);

            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());


            mViewPager = (ViewPager) findViewById(R.id.container);
            mViewPager.setAdapter(mSectionsPagerAdapter);
            mViewPager.setOffscreenPageLimit(2);

            TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setupWithViewPager(mViewPager);




        }

         static SearchView searchView;
    static ArrayList<ListView> lists=new ArrayList<>();
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            getMenuInflater().inflate(R.menu.menu_home_search, menu);
            searchView=(SearchView) menu.findItem(R.id.menu_search).getActionView();
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }
                @Override
                public boolean onQueryTextChange(String newText) {

                    final TabLayout tabHost = (TabLayout) findViewById(R.id.tabs);
                    for(int i=lists.size()-1;i>=0;i--) {
                        final int Fi=i;
                        CustomAdapter adapter = (CustomAdapter) lists.get(i).getAdapter();
                        if (adapter != null) {//for searching
                            adapter.getFilter(Arrays.asList(1, 3, 7)).filter(searchView.getQuery().toString().trim());/*,new Filter.FilterListener() {
                                public void onFilterComplete(int count) {
                                    if(count>0){
                                        try {
                                            tabHost.getTabAt(Fi).select();
                                        }
                                        catch (Exception e){
                                          Common.toastMessage(InvoiceSummary.this,e.getMessage());
                                        }
                                    }
                                }
                            });*/
                        }
                    }
                    return false;
                }
            });
            return true;
        }

        static ArrayList<ListView> pre=new ArrayList<>();



        public static class PlaceholderFragment extends Fragment {


            private static final String ARG_SECTION_NUMBER = "section_number";

            public PlaceholderFragment() {
            }

            public static PlaceholderFragment newInstance(int sectionNumber) {
                PlaceholderFragment fragment = new PlaceholderFragment();
                Bundle args = new Bundle();
                args.putInt(ARG_SECTION_NUMBER, sectionNumber);
                fragment.setArguments(args);
                return fragment;
            }

            @Override
            public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {





                final View rootView = inflater.inflate(R.layout.fragment_previous, container, false);
                final LinearLayout fragmentLinear=(LinearLayout)rootView.findViewById(R.id.fragment_linear);

                final ListView invoiceList=(ListView)rootView.findViewById(R.id.invoice_list);
                pre.add(invoiceList);






                if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {//date-wise


                    final View invoiceHeader = inflater.inflate(R.layout.item_previous_header, null);
                    fragmentLinear.addView(invoiceHeader);
                    (invoiceHeader.findViewById(R.id.dates_layout)).setVisibility(View.VISIBLE);
                    startDate = (TextView) invoiceHeader.findViewById(R.id.start_date);
                    endDate = (TextView) invoiceHeader.findViewById(R.id.end_date);

                    List<String> options = new ArrayList<String>();
                    options.add(ALL);
                    options.add(PAYMENTS);
                    options.add(EXPENSES);

                    final Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner1);
                    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, options);



                    dataAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                    dataAdapter.setDropDownViewResource(R.layout.item_spinner);
                    spinner.setAdapter(dataAdapter);








                    Calendar c = Calendar.getInstance();
                    c.add(Calendar.MONTH, -1);
                    Calendar today = Calendar.getInstance();

                    SimpleDateFormat formatted = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
                    startDate.setText(formatted.format(c.getTime()));
                    endDate.setText(formatted.format(today.getTime()));
                    getDateWiseInvoices(rootView,invoiceHeader,invoiceList);
                    View.OnClickListener onClickListener=new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            final TextView requiredDate=(TextView)v;
                            final String oldText=requiredDate.getText().toString();
                            final Calendar today = Calendar.getInstance();
                            final Calendar selectedDate=Calendar.getInstance();
                            DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                    selectedDate.set(Calendar.YEAR, year);
                                    selectedDate.set(Calendar.MONTH, monthOfYear);
                                    selectedDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                                    //Setting display text-------
                                    SimpleDateFormat formatted = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
                                    requiredDate.setText(formatted.format(selectedDate.getTime()));
                                    //Validation--------------
                                    if(!startDate.getText().toString().equals(getResources().getString(R.string.start_date))
                                            &&!endDate.getText().toString().equals(getResources().getString(R.string.end_date))){
                                        try {
                                            Date sDate=formatted.parse(startDate.getText().toString());
                                            Date eDate=formatted.parse(endDate.getText().toString());
                                            if(sDate.after(eDate)){
                                                Common.toastMessage(getContext(),R.string.give_valid);
                                                requiredDate.setText(oldText);
                                                return;
                                            }
                                        } catch (ParseException e) {
                                            requiredDate.setText(oldText);
                                            return;
                                        }
                                        getDateWiseInvoices(rootView,invoiceHeader,invoiceList);
                                    }
                                }
                            };
                            new DatePickerDialog(getContext(), dateSetListener, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH)).show();

                        }
                    };
                    startDate.setOnClickListener(onClickListener);
                    endDate.setOnClickListener(onClickListener);
                }
                return rootView;
            }

            void getDateWiseInvoices(final View rootView,final View invoiceHeader,final ListView invoiceList){


                (rootView.findViewById(R.id.no_items)).setVisibility(View.GONE);

                (rootView.findViewById(R.id.list_card)).setVisibility(View.GONE);
                invoiceList.setAdapter(null);


                final Common common = new Common();
                String webService = "/API/Approver/GetPreviousApprovalsInfo";
                String postData = "{\"FromDate\":\"" + startDate.getText().toString() + "\",\"ToDate\":\"" + endDate.getText().toString() + "\"}";
                AVLoadingIndicatorView loadingIndicator = (AVLoadingIndicatorView) rootView.findViewById(R.id.loading_indicator);
                String[] dataColumns = {};
                Runnable postThread = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONArray invoices = new JSONArray(common.json);
                            if(invoices.length()==0){
                                (rootView.findViewById(R.id.no_items)).setVisibility(View.VISIBLE);
                                return;
                            }
                            ArrayList<String[]> invoiceListData = new ArrayList<>();
                            for (int i = 0; i < invoices.length(); i++) {
                                JSONObject jsonObject1 = invoices.getJSONObject(i);
                                String[] data = new String[8];
                                data[0] = jsonObject1.getString("ID");
                                data[1] = jsonObject1.getString("EntryNo");
                                data[2] = jsonObject1.getString("Company");
                                data[3] = jsonObject1.getString("Date");
                                data[4] = jsonObject1.getString("PaymentMode");
                                data[5] = jsonObject1.getString("Amount");
                                data[6] = jsonObject1.getString("Type");
                                data[7] = jsonObject1.getString("ApprovalDate");


                                invoiceListData.add(data);
                            }

                            CustomAdapter adapter = new CustomAdapter(getContext(), invoiceListData, Common.PREVIOUSPAYMENTS);
                            invoiceList.setAdapter(adapter);
                            (rootView.findViewById(R.id.list_card)).setVisibility(View.VISIBLE);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }



                    }
                };

                Runnable postThreadFailed = new Runnable() {
                    @Override
                    public void run() {
                        Common.toastMessage(getContext(), R.string.failed_server);
                    }
                };

                common.AsynchronousThread(getContext(),
                        webService,
                        postData,
                        loadingIndicator,
                        dataColumns,
                        postThread,
                        postThreadFailed);
                asyncTasks.add(common.asyncTask);


            }

           SearchView searchView;


        }

        public static class SectionsPagerAdapter extends FragmentPagerAdapter {

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

            @Override
            public Fragment getItem(int position) {

                return PlaceholderFragment.newInstance(position + 1);
            }

            @Override
            public int getCount() {

                return 1;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {

                    case 1:
                        return "Date wise";
                }
                return null;
            }
        }

    }






    //How to make display seperate list using adapter call when pressing spinner items.

//我的适配器类

public class CustomAdapter extends BaseAdapter {
    private Context adapterContext;
    public static LayoutInflater inflater=null;
    private ArrayList<String[]> objects;
    private String calledFrom;
    private SimpleDateFormat formatted;
    private Calendar cal;
    CustomAdapter(Context context, ArrayList<String[]> objects, String calledFrom) {

        initialization(context, objects, calledFrom);
    }
    void initialization(Context context, ArrayList<String[]> objects, String calledFrom){
        adapterContext=context;
        inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.objects=objects;
        this.filteredObjects=objects;
        this.calledFrom=calledFrom;

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

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class Holder {

        TextView entryN,compN,payD,payM,payA,payT,appD;


    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder;
        final int fPos=position;
        switch (calledFrom) {


          case Common.PREVIOUSPAYMENTS:
                if (convertView == null) {
                    holder = new Holder();
                    convertView = inflater.inflate(R.layout.item_previous_approvals, null);
                    holder.entryN = (TextView) convertView.findViewById(R.id.entry_no);
                    holder.compN=(TextView)convertView.findViewById(R.id.company_name);
                    holder.payD=(TextView)convertView.findViewById(R.id.payment_date);
                    holder.payM=(TextView)convertView.findViewById(R.id.payment_mode);
                    holder.payA=(TextView)convertView.findViewById(R.id.payment_amount);
                    holder.payT=(TextView)convertView.findViewById(R.id.payment_type);
                    holder.appD=(TextView)convertView.findViewById(R.id.approval_date);
                    convertView.setTag(holder);
                } else {
                    holder = (Holder) convertView.getTag();
                }

//              holder.paidAmount.setText((filteredObjects.get(position)[6].equals("null")?"-":adapterContext.getResources().getString(R.string.paid_amount,filteredObjects.get(position)[6])));
                holder.entryN.setText((filteredObjects.get(position)[1].equals("null")?"-":filteredObjects.get(position)[1]));
                holder.compN.setText((filteredObjects.get(position)[2].equals("null")?"-":filteredObjects.get(position)[2]));
                holder.payD.setText((filteredObjects.get(position)[3].equals("null")?"-":filteredObjects.get(position)[3]));
                holder.payM.setText((filteredObjects.get(position)[4].equals("null")?"-":filteredObjects.get(position)[4]));
                holder.payA.setText((filteredObjects.get(position)[5].equals("null")?"-":adapterContext.getResources().getString(R.string.paid_amount,filteredObjects.get(position)[5])));
                holder.payT.setText((filteredObjects.get(position)[6].equals("null")?"-":filteredObjects.get(position)[6]));
                holder.appD.setText((filteredObjects.get(position)[7].equals("null")?"-":adapterContext.getResources().getString(R.string.Ap_date,filteredObjects.get(position)[7])));
                break;










        }
        return convertView;
    }


    private ItemFilter mFilter = new ItemFilter();
    private ArrayList<String[]> filteredObjects;
    private List<Integer> dataItemPosition;
    Filter getFilter(List<Integer> dataItem) {
        dataItemPosition=dataItem;
        return mFilter;
    }
    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            String filterString = constraint.toString().toLowerCase();
            FilterResults results = new FilterResults();
            int count = objects.size();
            final ArrayList<String[]> filteredList = new ArrayList<String[]>(count);

            for (int i = 0; i < count; i++) {
                for(int j=0;j<dataItemPosition.size();j++) {
                    if (objects.get(i)[dataItemPosition.get(j)].toLowerCase().contains(filterString)) {
                        filteredList.add(objects.get(i));
                        break;//found at least one item
                    }
                }
            }

            results.values = filteredList;
            results.count = filteredList.size();
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredObjects = (ArrayList<String[]>) results.values;
            notifyDataSetChanged();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个: -

enterList<String> options = new ArrayList<String>();
options.add(ALL);
options.add(PAYMENTS);
options.add(EXPENSES);
String[] values = {"ALL", "PAYMENTS", "EXPENSE"};
final Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner1);
ArrayAdapter dataAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, options);

dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (spinner.getSelectedItem().toString()) {
            case ALL:
                invoiceList.setAdapter(aadapter);
                break;
            case PAYMENTS:
                invoiceList.setAdapter(aadapter);
                break;
            case EXPENSES:
                invoiceList.setAdapter(aadapter);
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
 }); 

如需更多帮助,请参阅此链接: - https://developer.android.com/guide/topics/ui/controls/spinner.html