按每个Cardview中的编号订购Cardviews

时间:2018-10-02 04:38:12

标签: android

我目前已经知道了,所以当用户按下FAB时,卡片视图会添加到回收站视图中。每个Cardview内都有一个微调框,eddittext,textview和复选框。

微调框由csv的一列中的项目填充。当用户从微调器中选择一个项目时,同一csv中另一列中与该项目对应的核心编号显示在同一cardview的textview中。

所以我的应用程序看起来像这样,数字就是textviews。

enter image description here

问题我想知道是否有可能,这样当用户从微调器中选择一个项目并在文本视图中显示该数字时,是否有可能使卡片视图自动按顺序排序每个Cardview中的数字是多少?因此,按照上面的图片,如果要订购它,将会是这样吗?

土豆片-0

咖啡-1

巧克力-6

冰淇淋-14

ProductAdapter.java

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {

    private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();

    private Map<String, String> numberItemValues = new HashMap<>();

    private List<Product> productList;

    private Activity create;


    //TODO CODE FOR CSV FILE


    InputStream inputStream = null;
    List<String>  mSpinnerItems = null;
    CSVFile csvFile = null;


    //TODO END OF CODE FOR CSV FILE

    public ProductAdapter(Activity activity) {
        create = activity;

    }



    public ProductAdapter(Activity activity, List<Product> productList, Map<String, String> numberList) {
        numberItemValues = numberList;
        create = activity;
        this.productList = productList;
    }

    @Override
    public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //inflating and returning our view holder
        LayoutInflater inflater = LayoutInflater.from(create);
        View view = inflater.inflate(R.layout.layout_products, null);
        return new ProductViewHolder(view);
    }

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


        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(create, R.layout.item_spinner_layout,
                Product.getSpinnerItemsList());
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        holder.spinner.setAdapter(spinnerArrayAdapter);

        holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
                mSpinnerSelectedItem.put(position, mPosition);

                TextView mTextView = view.findViewById(R.id.mSpinnerText);

                String currentItem = holder.spinner.getItemAtPosition(mPosition).toString();

                Set<String> set = numberItemValues.keySet(); for(String key : set) {String value = numberItemValues.get(key);
                    Log.e("DATA ", "key = " + key + " value = " + value); }

                String aisleNumber = numberItemValues.get(currentItem);
                holder.textView5.setText(aisleNumber);

                Log.e("SELECTION TEST", " Selected map item = " + aisleNumber );

            }

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

            }
        });

        //binding the data with the viewholder views
        if (mSpinnerSelectedItem.containsKey(position)) {
            holder.spinner.setSelection(mSpinnerSelectedItem.get(position));
        }


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


                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);


                // set title
                alertDialogBuilder.setTitle("Delete Item");

                // set dialog message
                alertDialogBuilder
                        .setMessage("Are you sure you want to delete this item?")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, close
                                // current activity


                                holder.checkBox.setChecked(false);
                                holder.spinner.setSelection(0);

                                productList.remove(holder.getAdapterPosition());
                                notifyItemRemoved(holder.getAdapterPosition());

                                Toast.makeText(create, "Item removed.", Toast.LENGTH_LONG).show();


                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            }
                        });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();

            }
        });

    }


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

    public void reset() {


       /* holder.checkBox.setChecked(false);
        holder.spinner.setSelection(0);*/

        productList.clear();
        notifyDataSetChanged();

    }

    class ProductViewHolder extends RecyclerView.ViewHolder {

        SearchableSpinner spinner;
        EditText editText;
        TextView textView5;
        CheckBox checkBox;
        LinearLayout linearLayout;
        View rootView;


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

            spinner = itemView.findViewById(R.id.spinner);
            editText = itemView.findViewById(R.id.editText);
            textView5 = itemView.findViewById(R.id.textView5);
            checkBox = itemView.findViewById(R.id.checkBox);
            rootView = itemView.findViewById(R.id.linearLayout);


            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // makes the set disappear when checkbox is ticked.
                    if(isChecked){

                        checkBox.setChecked(false);
                        spinner.setSelection(0);

                        productList.remove(getAdapterPosition());
                        notifyItemRemoved(getAdapterPosition());



                        Toast.makeText(create, "Done!", Toast.LENGTH_LONG).show();
                    }

                }
            });



        }

        public View getView() {
            return rootView;
        }

    }


    //TODO CODE FOR CSV FILE
    private class CSVFile {
        InputStream inputStream;

        public CSVFile(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public List<String> read() {
            List<String> resultList = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] row = line.split(",");

                    numberItemValues.put(row[1], row[0]);

                    resultList.add(row[1]);
                }
            } catch (IOException e) {
                Log.e("Main", e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("Main", e.getMessage());
                }
            }
            return resultList;
        }
    }


}

create.java,这是我添加卡视图等的屏幕的主要活动代码

public class create extends AppCompatActivity {



    //a list to store all the products
    List<Product> productList;

    //the recyclerview
    RecyclerView recyclerView;


    Product mProduct;
    private Map<String, String> numberItemValues = new HashMap<>();
    private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();


   // RelativeLayout relativeLayout;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create);
        findViewById(R.id.relativeLayout).requestFocus();







        findViewById(R.id.relativeLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) view.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        });






        //opens csv
        InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
         CSVFile csvFile = new CSVFile(inputStream);

       final List<String>  mSpinnerItems = csvFile.read();


        //getting the recyclerview from xml
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        //initializing the productlist
        productList = new ArrayList<>();
        productList.add(new Product(mSpinnerItems, "Test Edit Text",false, "Text String 2"));




        final ProductAdapter  adapter = new ProductAdapter(this, productList, numberItemValues);


        //TODO FAB BUTTON
        FloatingActionButton floatingActionButton =
             findViewById(R.id.fab);


        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                productList.add(mProduct);
                if(adapter != null)
                    adapter.notifyDataSetChanged();


                //Handle the empty adapter here

            }
        });









        //setting adapter to recyclerview
        recyclerView.setAdapter(adapter);









    }




    //TODO OVERFLOW MENU
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_delete) {



            ((ProductAdapter) recyclerView.getAdapter()).reset();

            Toast.makeText(create.this,
                    "Shopping List Deleted.", Toast.LENGTH_LONG).show();

            return true;
        }


        if (id == R.id.action_help) {


            // setup the alert builder
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Help");
            builder.setMessage("Click the button in the bottom right corner to add an item. Touch the dropdown menu and begin typing" +
                    "the item you want. The aisle number will then show. You are also able to enter in the quantity you want, for your reference." +
                    "If you made a mistake you can always click the surrounding white box to delete the item. Once you have got the item you" +
                    "can touch the checkbox. If you want to delete your whole list, press the menu button on your device or the 3 dots in the corner and press" +
                    "delete.");

            // add a button
            builder.setPositiveButton("OK", null);

            // create and show the alert dialog
            AlertDialog dialog = builder.create();
            dialog.show();


        }





        return super.onOptionsItemSelected(item);
    }








    private class CSVFile {
        InputStream inputStream;

        public CSVFile(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public List<String> read() {
            List<String> resultList = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] row = line.split(",");
                    //TODO I edited this part so that you'd add the values in our new hash map variable

                    numberItemValues.put(row[1], row[0]);

                    resultList.add(row[1]);
                }
            } catch (IOException e) {
                Log.e("Main", e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("Main", e.getMessage());
                }
            }
            return resultList;
        }
    }



}

1 个答案:

答案 0 :(得分:2)

订阅微调框选择事件。当它触发时,您必须到达数据集合并对其进行排序,然后才通知适配器adapter.notifyDataSetChanged()

您是否正在使用recyclerview或?

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
         @Override
         public void onItemSelected(AdapterView<?> adapterView, View view,
                    int position, long id) { 
     adapter.sortDataSet();
});

在适配器中:

public void sortDataSet(){
  //sort dataSet (arrayList, etc)
  notifyDataSetChanged();
}

对数据进行排序很容易。有很多不同的方法,一种方法必须覆盖类方法,而另一种方法则必须创建其他对象或为类添加合同。 您可以在此处找到很多示例:h

Microsoft's Application Gateway FAQ

如果您使用java8,我会建议这样的事情: list.sort((a,b)-> a.field> b.field);

class Product implements Comparable<Product> { 
@Override
public int compareTo(Product other) {
    return Integer.compare(this.IntField, other.IntField);
}
}