Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

android - Taking the state of one activity to another

I have two activity screens: Create and View. Create is where the user creates their shopping list. View is where they view their list (and can still add items).

UPDATE: Some may say why not just use the one activity instead of having both activities the same basically but this is how I've planned it out. I want it so when you add spinners by pressing the FAB on the create screen, you can select values from those. Then when you go back to the main menu, then to the view screen, those spinners and the selected values from the create screen appear here too. Additionally I want it so when you close the app and reopen it, all the spinners and values that you selected still appear. If there are any questions please comment.

I do appreciate the posts below with the examples however I'm just confused as to if it fits my situation or not!

Below is my create.java code. (view.java has exactly the same code just with .view in places instead of .create, and some extra code.)

create.java

public class create extends AppCompatActivity {


    private LinearLayout mLinearLayout;
    private ArrayList<SearchableSpinner> mSpinners;
    private List<AppCompatButton> mButtons = new ArrayList<>();
    private List<CheckBox> mCheckboxes = new ArrayList<>();
    private List<TextView> mTextviews = new ArrayList<>();
    private List<EditText> mEdittexts = new ArrayList<>();
    private List<View> mViews = new ArrayList<>();
    private Map<String, String> numberItemValues = new HashMap<>();
    List<String> itemList = new ArrayList<>();
    //Button buttontest;
    // TextView textview;
    // CheckBox checkbox;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        GlobalClass globalClass = (GlobalClass) this.getApplicationContext();


        ArrayList<String> items = new ArrayList<>();
        items.add(String.valueOf(mSpinners)); // add you selected item
        globalClass.setItems(items);


        mSpinners = new ArrayList<>();

        mLinearLayout = findViewById(R.id.my_linearLayout);


        //code for the add button to add more items
        FloatingActionButton floatingActionButton =
                (FloatingActionButton) findViewById(R.id.fab);

        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getBaseContext(), "Item added!", Toast.LENGTH_SHORT).show();


                // Handle ze click.
                final Spinner spinner = makeSpinner();
                mLinearLayout.addView(spinner);


                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) spinner.getLayoutParams();
                layoutParams.setMargins(5, 100, 10, 0); //top 70

                Resources resources = getResources();
                DisplayMetrics metrics = resources.getDisplayMetrics();

                layoutParams.height = (int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //80
                layoutParams.width = (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //240
                spinner.setLayoutParams(layoutParams);

                final View newView = makeView();
                //Add a new view
                mLinearLayout.addView(newView);
                mViews.add(newView);


                final EditText newEdittext = makeEdittext();
                mLinearLayout.addView(newEdittext);
                mEdittexts.add(newEdittext);


                final int listSize = mViews.size();


                //code for deleting the said item.
                newView.setOnClickListener(new View.OnClickListener() {
                    //start
                    @Override
                    public void onClick(View view) {

                        //when the 'new button' is pressed, alert shows if you are sure you want to delete the item or not.

                        final View.OnClickListener context = this;


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


                        // 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


                                        if (listSize > 0) {

                                            mCheckboxes.get(listSize - 1).setVisibility(View.GONE);
                                            mSpinners.get(listSize - 1).setVisibility(View.GONE);
                                            mViews.get(listSize - 1).setVisibility(View.GONE);
                                            mTextviews.get(listSize - 1).setVisibility(View.GONE);
                                            mEdittexts.get(listSize - 1).setVisibility(View.GONE);
                                            Toast.makeText(getBaseContext(), "Item removed.", Toast.LENGTH_SHORT).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();


                    }
                });


                //Add a new checkbox
                final CheckBox newCheckbox = makeCheckbox();
                mLinearLayout.addView(newCheckbox);

                //TODO add checkbox to your list
                mCheckboxes.add(newCheckbox);


                final TextView newTextview = makeTextview();
                mLinearLayout.addView(newTextview);
                mTextviews.add(newTextview);

                //TODO Add the spinner on item selected listener to get selected items
                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                        String currentItem = itemList.get(position);
                        String aisleNumber = numberItemValues.get(currentItem);
                        //TODO you can use the above aisle number to add to your text view
                        //mTextviews.get(mTextviews.size() -1).setText(aisleNumber);
                        newTextview.setText(aisleNumber);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parentView) {
                        //  code here
                    }

                });


            }
        });

    }










   /* //creates the 3 buttons on the side.
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.create_menu, menu);
        return true;
    }
*/





    //use a relative layout and specify which ones are to layout_toRightOf and layout_below

    //DUPLICATING ITEMS WHEN FAB IS PRESSED//
    private CheckBox makeCheckbox() {
        //Create new Checkbox
        CheckBox checkbox = new CheckBox(this);

        // Setup layout
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);


        //setup relative layout for the positioning of the objects

       /* RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
                relativeParams.addRule(RelativeLayout.RIGHT_OF, textview); //can't  resolve symbol textview
                )

        checkbox.setLayoutParams(relativeParams);*/
        checkbox.setLayoutParams(layoutParams);
        return checkbox;
    }


    private TextView makeTextview() {
        //create new textview
        TextView textview = new TextView(this);

        //setup layout

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        textview.setLayoutParams(layoutParams);
        textview.setText("ihi");


        return textview;
    }


    private EditText makeEdittext() {
        //create new edittext
        EditText edittext = new EditText(this);

        //setup layout
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(50, 50); // Width , height
        edittext.setLayoutParams(lparams);
        edittext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);

        return edittext;

    }




    private View makeView() {
        //create new View

        View view = new View(this);
        view.setBackgroundColor(Color.parseColor("#ffffff"));
        LinearLayout.LayoutParams layoutParams =  new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 100);
        new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, 50);
        //LinearLayout.LayoutParams.MATCH_PARENT,
        // LinearLayout.LayoutParams.WRAP_CONTENT);
        view.setClickable(true);




        view.setLayoutParams(layoutParams);


        //setup layout

        return view;


    }






    private Spinner makeSpinner() {
        //opens csv
        InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
        CSVFile csvFile = new CSVFile(inputStream);
        //TODO I made this variable global, declared it at the very top of this file
        itemList = csvFile.read();

        //Create new spinner
        // SearchableSpinner spinner = (SearchableSpinner) new Spinner(this, Spinner.MODE_DROPDOWN);
        SearchableSpinner spinner = new SearchableSpinner(this);


        // Setup layout
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        spinner.setLayoutParams(layoutParams);
        MyListAdapter adapter = new MyListAdapter(this, R.layout.listrow, R.id.txtid, itemList);


        spinner.setAdapter(adapter);



        //Add it to your list of spinners so you can retrieve their data when 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[UPDATED]

So basically, you have 2 activity classes, create and view (as you mentioned).

Declare your spinner in the form of global. All other explanation of the code is in the form of comment.

public class create extends AppCompatActivity {

private LinearLayout mLinearLayout;
private ArrayList<SearchableSpinner> mSpinners;
//TODO add the below list of buttons and checkboxes
//private List<AppCompatButton> mButtons = new ArrayList<>();
private List<CheckBox> mCheckboxes = new ArrayList<>();
private List<View> mViews = new ArrayList<>();

Button buttonGo;

//define spinner here
Spinner spinner;


//your own code
......
floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getBaseContext(), "Item added!", Toast.LENGTH_SHORT).show();

            RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
            RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
            // Handle the click.


            //initialise your spinner here
            spinner = makeSpinner();

            //your code as usual
        }

    //put this some where in your code where you want to start another activity after your operations are done (usually in onClick of something)
    {
        Intent i= new Intent(this, YourSecondClass.class);
        //Create the bundle
        Bundle bundle = new Bundle();

        //Add your data to bundle one by one, in this case passing spinner selected value, 
        //replace val1 with your own variable name
        bundle.putString("val1", spinner.getSelectedItem().toString());

        //if you have more spinner,add in similar way
        bundle.putString("val2", spinner2.getSelectedItem().toString());

        //Add the bundle to the intent
        i.putExtras(bundle);
        startActivity(i);
    }


}
}

Here is the sample for view activity.

public class view extends AppCompatActivity {

...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        //initialise your spinner here
        spinner = makeSpinner();

        //Get bundle from previous intent(activity)
        Bundle bundle = getIntent().getExtras();

        //Extract the data…
        String val1= bundle.getString("val1");
        String val2= bundle.getString("val2");

        //USUALLY, you will have a list of items in your spinner, do what you should do, this is just an example.
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //set the adapter
        mSpinner.setAdapter(adapter);


        if (val1 != null) {
            int spinnerPosition = adapter.getPosition(val1);
            spinner.setSelection(spinnerPosition);
        }       
        ...


    }
...

}

NOTE: This is just a guidance or 'framework' to give you some clues on where you should place your code. NOT FULL SOLUTION as your code is too long and I can't assure its correct, so I did not include them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...