【问题标题】:Taking the state of one activity to another将一项活动的状态转移到另一项活动
【发布时间】:2019-01-20 22:03:57
【问题描述】:

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

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

我很欣赏下面带有示例的帖子,但我只是对它是否适合我的情况感到困惑!

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

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>

【问题讨论】:

标签: android


【解决方案1】:

[更新]

所以基本上,您有 2 个活动课程,createview(正如您所提到的)。

以全局的形式声明你的微调器。代码的所有其他解释都是以注释的形式。

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


}
}

这是view 活动的示例。

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


    }
...

}

注意:这只是一个指导或“框架”,可以为您提供一些关于应该将代码放置在何处的线索。不完整的解决方案,因为您的代码太长,我无法保证其正确性,所以我没有包含它们。

【讨论】:

  • 我的意思是在你的第一个活动中,当你开始你的第二个活动时,你可以使用 bundle 来传递值
  • 我的错,我的意思是微调器,只需使用微调器的 onItemSelected,并在该方法中有一个变量,一旦用户选择,它将选择的值存储到一个变量中,你可以做什么我在上面写了
  • 你可以学习android编程的基础知识,从这里开始另一个活动:developer.android.com/training/basics/firstapp/…
  • 没问题,但是建议你先学习简单的基础知识再去,因为你可能不理解这里的大部分答案,对基础知识有了更好的理解,你会很容易做任何你想做的事.如果我帮助了你,标记为答案。快乐编码
  • @Magic_Whizz 在这里更新,注意,所有值得注意的东西都在代码中注释
【解决方案2】:
buttonGo.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
if(spinner!=null){

Intent i= new Intent(create.this, viewscreen.class);
//Create the bundle
Bundle bundle = new Bundle();

//Add your data to bundle
bundle.putString("dropdown", dropdown_value);

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

【讨论】:

  • 好的。我想我已经把括号塞在某个地方了,因为代码在 onCreate 中,但是微调器仍然无法识别?
  • 这就是为什么你检查微调器是否为空,如果不是它不会去其他活动
  • 哦耶,像定义按钮一样定义微调器
  • 我在 buttonGo 代码中添加了SearchableSpinner spinner = new SearchableSpinner(this);。 (我在 makeSpinner 方法中得到了这段代码)但是 this 是红色的底线**
  • .... 无语.... 只需从您的 onClick 下的 final Spinner spinner 中删除 final Spinner,并声明变量 global
【解决方案3】:

此场景的最佳解决方案是使用架构组件库中的 ViewModel 和 LiveData,这将为您提供两个活动中数据的一致性。两个活动的单个 ViewModel 和两个活动的共享 LiveData,当您从任何 Activity 更新任何 LiveData 时,这将很有帮助,它将反映在所有正在观察 ViewModel 中定义的 LiveData 的活动中。

【讨论】:

    【解决方案4】:
    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;
    Spinner spinner;
    ......
    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.
    
    
                // Handle ze click.
                //final Spinner spinner = makeSpinner();
                //mLinearLayout.addView(spinner);
    
                spinner = makeSpinner();
    }
    

    【讨论】:

    • 我从 logcat 收到一个错误。在帖子中更新了它
    • 你更新了所有代码吗?所以我可以知道哪条线可能发生
    • 现在更新了代码。它发生在我声明 buttonGo onclicklistener 的那一行
    • 我猜你忘了做作业:(Button) findViewById(R.id.buttongo);像这样的
    • 好的。但我认为有问题。因为当我通过单击 FAB 添加一些微调器然后单击按钮转到视图屏幕时,没有微调器存在
    【解决方案5】:

    您将上下文称为“This”,但从覆盖接口中方法的方法中调用它,但该方法不在此类中,因此不知道“This”是什么,解决它这样做,在你创建类:

    public class Create extends AppCompatActivity {
      private Context context;
      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_view);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            context = this;
            buttonGo.setOnClickListener(new View.OnClickListener() {
                                            public void onClick(View v) {
    
                                                if(spinner!=null){
    
                                                    Intent i= new Intent(context, View.class);
                                                    startActivity(i);
                                                }
                                            };
      }
    }
    

    您可以根据意图传递数据,也可以使用 Create 类中的静态变量传递数据。

    创建类:

        public class Create extends AppCompatActivity {
            public static String optionSelected;
    //other code....
                spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                              Create.optionSelected = parent.getItemAtPosition(position).toString();  
                            }
                        });
    //other code....
    
                }
    

    在你的视图类中调用 optionSelected:

    public class View extends AppCompatActivity {
    
     String dropdown_value= Create.optionSelected;
    
      // rest of code
    }
    

    如果你想使用类别适配器类:

    public class CategoryAdapter extends FragmentPagerAdapter {
    
        public CategoryAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    return new CreateFragment();
                case 1:
                    return new ViewFragment();
                default:
                    return null;
            }
        }
    
        @Override
        public int getCount() {
            return 2;
        }
    }
    

    【讨论】:

    • 我有点回到我以前的代码;我,我真的不想要它,所以有 buttonGo 它带你从创建 > 视图。我只想要它,就像 Main > create,main > view。这种方式还有可能吗
    • 就像我的意思一样,不使用 startActivity
    • 您好 @Magic_Whizz 我需要查看您的 create_layout.xml 以及您希望它的外观如何?
    • 我认为你应该使用片段和类别适配器类,请给我看你的布局 xml,我会向你解释它是如何完成的。请查看我的编辑答案,以查看类别适配器类。
    • 我已经添加了我的布局 xml,但它并没有说太多,因为我在用户按下 FAB 时以编程方式添加微调器。谢谢,我会看看你的代码:)
    【解决方案6】:

    我不知道你为什么仍然陷入这个问题。当您知道在活动中传递值时。如果我想到您的问题,我会想到各种解决方案。

    解决方案 1: 使用 @Angus 解决方案,当您按照他的回答时,我检查了您的代码。

    基本上,您必须将值传递给下一个活动,例如位置/微调器选择的值。

    bundle.putString("selectedPos", spinner.getSelectedItemPosition());
    

    bundle.putString("selectedItem", ((String) spinner.getSelectedItem()));
    

    解决方案 2:您有 SharedPreference 将这些值存储在第一个活动中,然后在第二个活动中获取保存的值。

    解决方案 3: 我不建议使用 Application 类来存储变量,但是是的!,这是一个解决方案。喜欢this answer。我不使用 Application 类来存储值,因为我们需要在手动使用后清除字段,以恢复 RAM 使用

    解决方案 4: 正如您所说,您的两个活动几乎相同,那么您为什么不只使用一个活动并相应地管理视图。

    编辑

    如果我说对了,那么您可以将生成的 Spinners 项目列表和选定项目传递给下一个 Activity。您可以轻松传递 Parcelable List

    第一个 Activity 通过 Spinner 模型列表。

    ArrayList<ModelSpinner> list = new ArrayList<>();
    list.add(new ModelSpinner(itemsList, (String) spinner.getSelectedItem()));
    startActivity(new Intent(this, MainActivity.class).putParcelableArrayListExtra("key", list));
    

    第二个活动获取列表并做出相应的看法

    ArrayList<ModelSpinner> list = getIntent().getParcelableArrayListExtra("key");
    for (ModelSpinner spinner : list) {
    //            render spinners
        Spinner spinner = makeSpinner(spinner.getItems(),spinner.getSelectedValue());
        // todo create method makeSpinner(List<String> list, String selectedItem), add this spinner to your activity.
    }
    

    ModelSpinner.class

    public class ModelSpinner implements Parcelable {
        private ArrayList<String> items;
        private String selectedValue;
    
        // getter setter
    
        public ModelSpinner(ArrayList<String> items, String selectedValue){
           this.items = items;
           this.selectedValue = selectedValue;
        }
    
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeStringList(this.items);
            dest.writeString(this.selectedValue);
        }
    
        public ModelSpinner() {
        }
    
        protected ModelSpinner(Parcel in) {
            this.items = in.createStringArrayList();
            this.selectedValue = in.readString();
        }
    
        public static final Parcelable.Creator<ModelSpinner> CREATOR = new Parcelable.Creator<ModelSpinner>() {
            @Override
            public ModelSpinner createFromParcel(Parcel source) {
                return new ModelSpinner(source);
            }
    
            @Override
            public ModelSpinner[] newArray(int size) {
                return new ModelSpinner[size];
            }
        };
    }
    

    【讨论】:

    • 我知道如何从微调器中获取所选项目的值,但实际微调器本身呢?因为这些微调器是在您按下按钮时以编程方式添加的
    • 另外,我想要两个单独的活动,以便用户可以轻松区分这两个,即一个是您创建购物清单的位置,另一个是您查看它的位置,并且在也可以查看活动。
    • 您已经知道如何将 Spinner 添加到视图中,您只需要迭代接收到的列表,并以编程方式创建 Spinner。我也在添加一些待办事项。
    • 是的,你可以这么说!,实际上我向你展示了将你需要的所有值传递给下一个活动的方法,因为你不能只传递所有视图对象,所以你需要传递相关的值,然后在下一个活动中获取这些值(选定项目/所有项目)并重新创建视图。
    • 您将在下一个活动中获得ArrayList&lt;ModelSpinner&gt;,因此只需在此列表上循环并创建微调器
    【解决方案7】:

    我认为您想要做的是将用户选择的项目从创建屏幕传递到视图屏幕。

    您可以使用全局类来存储所选项目的值。并像普通的 java 类一样使用它。

    public class GlobalClass extends Application {
        ArrayList<String> items = new ArrayList<>();
    
        public ArrayList<String> getItems() {
            return items;
        }
    
        public void setItems(ArrayList<String> items) {
            this.items = items;
        }
    }
    

    在清单文件的应用标签中定义这个

    <application
        android:name=".GlobalClass"
    

    并在两个活动的onCreate 函数中像这样使用它

    globalClass = (GlobalClass) this.getApplicationContext();
    

    然后您可以使用 getter 和 setter 访问您选择的项目列表。 在创建活动中,

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

    查看活动,

    ArrayList<String> items = globalClass.getItems();
    

    【讨论】:

    • 我在manifest文件的什么地方定义了android:name=".GlobalClass"?
    • 在应用标签&lt;application android:name=".GlobalClass"
    • item = object 或您提到的下拉菜单中所选项目或项目的字符串值
    • 对不起,我没听懂你在问什么。
    • 但是如果您询问从创建视图中选择的下拉菜单,您必须使用使用此全局类传递的数据来创建它们。顺便说一句,您可以将下拉菜单的数据存储在全局类中,并从两个视图中访问它们。
    【解决方案8】:

    我也有类似的要求。我用不同的逻辑解决了它。

    1. 创建一个类以供参考。
    2. 在此类中存储数据,然后使用 Gson 进行字符串化并将其传递给第二个活动。
    3. 使用 Gson 从字符串化的 json 返回到类对象。
    4. OnCreate,根据第3步收到的对象内容更新UI。

    这将使控制和开发中的流程变得友好。希望这能很好地满足您的要求。

    存储视图并传输并不是一个更好的主意,因为这可能会导致以后的开发复杂性。

    如果n个spinner有多个数据,可以使用产品对象的ArrayList,动态创建spinner view。

    【讨论】:

      【解决方案9】:

      好吧,所以我建议做的是创建一个 ArrayListInteger 来跟踪您在第一个 ActivityArrayList.size() 中创建的 Spinner 的数量以及每个 Spinner 的位置,这将是ArrayList 中的值。

      所以首先在第一个Activity中点击一个按钮时把这段代码放在onClick方法中:

      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,如下所示:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-03
        • 2012-11-29
        • 2012-01-24
        相关资源
        最近更新 更多