在 类 之间移动 return 个变量

Moving return varibles between Classes

我在 Fragment 中有一个方法,它从数量 Spinner 中获取一个值并 returns 它。我在哪里可以检索这个变量的值?如果我想将它完全移到一个新的 Activity,我怎样才能在那里取回它?

public String SetupQuantitySpinner(String[] quantity) {
    Spinner spnr2;
    spnr2 = (Spinner)view.findViewById(R.id.spinner_quantity);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            getActivity(),
            R.layout.custom_spinner,
            R.id.text_main_seen,
            quantity);
    spnr2.setAdapter(adapter);
    return quantity[spnr2.getSelectedItemPosition()];
}

微调器基本上代表用户决定购买的商品数量,即 1 到 20 件衬衫。我现在必须将这个值乘以它的成本,但成本是在另一个 Activity 中检索到的:

String cost = currentProduct.getCost();

我需要将 quantity[spnr2.getSelectedItemPosition()] 发送到这个新的 Activity 以便我可以将它乘以 currentProduct.getCost();

我怎样才能做到这一点?

编辑: 这是不同的,因此不是重复的,因为我只想发送和检索与所选 Spinner 项目关联的数据。

如果您只想检索另一个 activity 中的选定项目,那么您只需将此代码放在 onItemSelected 方法中即可。并在 activity.

中检索 extra 的值
String item = mSpinner.getSelectedItem().toString();
Intent intent = new Intent(this,NextActivity.class);
intent.putExtra("item",item);
startActivity(intent);

这是另一种方法。写一个全局变量:

public final static String PRODUCT_SIZE_MESSAGE = "com.elgami.customizer.PRODUCT_SIZE";

在代码中您想要的地方开始您的 Intent:

Intent intent;
intent.putExtra(MainActivity.PRODUCT_QUANTITY_MESSAGE, productQuantity);
startActivity(intent);

您将要发送的变量与您的 Intent 一起放在 Extra 中,然后在新的 Class 中检索它,如下所示:

private int getIntentMessageProductQuantity() {
    return getIntent().getIntExtra(MainActivity.PRODUCT_QUANTITY_MESSAGE, 0);
}

现在您有了那个变量,您可以将它用作新 Class 中任何方法的参数,如下所示:

public void LaunchPurchaseIntent(MainActivity.ProductType productType, int productSize, int productQuantity, String uuid) throws ParseException {
    // Do what you want here

}