将一项活动的状态转移到另一项活动 [英] Taking the state of one activity to another

查看:56
本文介绍了将一项活动的状态转移到另一项活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个活动屏幕:创建和查看. 创建是用户创建购物清单的地方. 查看是他们查看列表的地方(并且仍然可以添加项目).

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).

更新: 有人可能会说为什么不只使用一个活动而不是使两个活动基本相同,而是我计划的方式.我想要这样,当您通过在创建屏幕上按FAB添加微调器时,可以从中选择值.然后,当您返回到主菜单,然后回到视图屏幕时,这些微调器和从创建"屏幕中选择的值也会显示在此处.另外,我想要它,所以当您关闭应用程序并重新打开它时,您选择的所有微调器和值仍然会出现.如有任何疑问,请发表评论.

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!

下面是我的create.java代码. (view.java具有完全相同的代码,只是在地方使用.view而不是.create,还有一些额外的代码.)

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 you click the getSpinner button
        mSpinners.add(spinner);
        return spinner;
    }



    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;
        }
    }}

创建xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackground"
    android:minHeight="170dp"
    tools:context=".create"
    tools:layout_editor_absoluteY="81dp">


    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView2"
        android:layout_width="match_parent"
        android:layout_height="438dp"
        android:fillViewport="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        tools:layout_editor_absoluteY="0dp">


        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/my_linearLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">


        </LinearLayout>


    </ScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="60dp"
        android:layout_height="70dp"
        android:layout_gravity="bottom|end"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="8dp"
        android:src="@android:drawable/ic_input_add"
        app:backgroundTint="@color/colorCreate"
        app:elevation="6dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:pressedTranslationZ="12dp"
        android:tint="@color/colorBackground"/>


    <View
        android:id="@+id/subheading"
        android:layout_width="match_parent"
        android:layout_height="83dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="1dp"
        android:layout_marginLeft="1dp"
        android:layout_marginRight="1dp"
        android:layout_marginStart="1dp"
        android:layout_marginTop="2dp"
        android:background="@color/colorBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        />

    <TextView
        android:id="@+id/example"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="492dp"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        android:hint="test"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/view"
        android:layout_width="320dp"
        android:layout_height="1dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="76dp"
        android:background="@color/colorText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/view2"
        android:layout_width="320dp"
        android:layout_height="1dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="28dp"
        android:background="@color/colorText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"

        android:layout_marginTop="12dp"
        android:fontFamily="@font/droid_sans"
        android:text="@string/done_label"
        android:textColor="@color/colorText"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView4"
        app:layout_constraintTop_toBottomOf="@+id/view2" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="128dp"
        android:layout_marginRight="128dp"
        android:layout_marginTop="8dp"
        android:fontFamily="@font/droid_sans"
        android:text="@string/aisle_label"
        android:textColor="@color/colorText"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view2"
        app:layout_constraintVertical_bias="1.0" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginEnd="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginTop="5dp"
        android:fontFamily="@font/droid_sans"
        android:text="@string/qty_label"
        android:textColor="@color/colorText"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/view"
        app:layout_constraintEnd_toStartOf="@+id/textView4"
        app:layout_constraintTop_toBottomOf="@+id/view2"
        app:layout_constraintVertical_bias="0.7" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="@font/droid_sans"
        android:text="@string/item_label"
        android:textColor="@color/colorText"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/view"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view2"
        app:layout_constraintVertical_bias="1.0" />


</android.support.constraint.ConstraintLayout>

推荐答案

好的,所以我建议做的是创建IntegerArrayList以跟踪您在第一个Activity中创建的Spinner的数量.到ArrayList.size()以及每个微调器的位置,该位置将是ArrayList中的值.

Alright so what I suggest doing is create an ArrayList of Integer to keep track of both the number of Spinners you created in the first Activity through ArrayList.size() and the position of each spinner which would be the value in the ArrayList.

因此,首先在第一个Activity中单击按钮时,将此代码放在onClick方法中:

So first when a button is clicked in the first Activity put this code in the onClick method:

ArrayList<Integer> spinnerList = new ArrayList<>(); 
for(int i = 0; i < mSpinners.size(); i++) { 
    spinnerList.add(mSpinners.get(i).getSelectedItemPosition()); 

} 
Bundle newBundle = new Bundle(); 
newBundle.putIntegerArrayList("arraylist", spinnerList); 
Intent newIntent = new Intent(create.this, view.class); 
newIntent.putExtra("extraBundle", newBundle);
startActivity(newIntent);

然后在第二个Activity(视图Activity)中获得ArrayList,如下所示:

And then in the second Activity (view Activity) get the ArrayList like this:

Intent gotIntent = getIntent();
Bundle bundle = getIntent().getBundleExtra("extraBundle");
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");

获取ArrayList后,创建与ArrayList大小相同的For loop次数,该大小是您拥有的微调器的数量,并添加用于添加微调器和其他视图的代码:

After getting the ArrayList create a For loop same number of times as the size of the ArrayList which is the number of spinners you had and add the code for adding the spinner and other views:

for(int i = 0; i < spinnerArrayList.size(); i++ { 
    //code for adding all views 

    //at the end of the loop 
    int positionOfSpinner = spinnerArrayList.get(i); 
    spinner.setSelection(positionOfSpinner);

}

这篇关于将一项活动的状态转移到另一项活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆