簡體   English   中英

如何將活動A中的EditText中的多個整數值傳遞給活動B中的文本視圖?

[英]How to pass multiple integer values from EditText in activity A to Text view in Activity B?

我有2個活動。

在活動A中,我有4個只能包含整數的EditTexts。 有一個按鈕,應該計算用戶輸入的4個數字的平均值。

在活動B中,有5個文本視圖(4個用於數字,1個用於結果)。 當按下活動A中的按鈕時。 它應該將活動A中的EditText中的數字傳遞給活動B中的文本視圖,還應該在結果文本視圖中顯示4個數字的平均值。

我觀看了很多教程,但它們僅用於一個值,當我嘗試復制多個值的代碼時,應用程序崩潰了。

一種方法是將值作為您用於啟動活動B的Intent的“額外”發送。

以下是活動A的可能代碼:

Intent i = new Intent(this, ActivityB.class);
i.putExtra("1", num1);
i.putExtra("2", num2);
i.putExtra("3", num3);
i.putExtra("4", num4);
i.putExtra("average", result);
startActivity(i);

此代碼假定您具有要在單獨的變量num1 - num4中發送的整數,並計算另一個名為“result”的變量的平均值。

要在活動B中解壓縮,您可以執行以下操作:

Intent i = getIntent();
textView1.setText(i.getIntExtra("1", 0); //0 is the default value in case the extra does not exist
textView2.setText(i.getIntExtra("2", 0);
textView3.setText(i.getIntExtra("3", 0);
textView4.setText(i.getIntExtra("4", 0);
resultView.setText(i.getIntExtra("average", 0));

您還可以將數字放在數組中,並使用一次調用putExtra和一次調用getIntArrayExtra 這會更優雅,但我想演示發送多個單獨的數字。

1.使用Intention Bundle通過

activityA代碼發送數據

Intent intent=new Intent(MainActivity.this,ActivityB.class);
    Bundle bundle=new Bundle();
    bundle.putInt("num1",10);
    bundle.putInt("num2",20);
    intent.putExtra("bun",bundle);
    startActivity(intent);

activityB代碼接收數據

Intent intent=getIntent();
    Bundle bundle=intent.getBundleExtra("bun");
    int num1=bundle.getInt("num1",0);
    int num2=bundle.getInt("num2",0);

2.使用序列化對象Seriazable

實現類

public class DataUtils implements Serializable {
 private int name;
 private int age;

    public String getName() {
         return name;
 }
 public void setName(int name) {
         this.name = name;
 }
 public int getAge() {
         return age;
 }
 public void setAge(int age) {
        this.age = age;
 }

}

activityA代碼發送數據

 Intent intent = new Intent(ActivityA.this,ActivityB.class);
 DataUtils dataUtils = new DataUtils();
 dataUtils.setAge(20);
 dataUtils.setName(10);
 intent.putExtra("du",dataUtils);
 startActivity(intent);

activityB代碼接收數據

 Intent intent=getIntent();
 Serializable serializable=intent.getSerializableExtra("du");
 if (serializable instanceof DataUtils){
  DataUtils db=(DataUtils) serializable;
  int name=db.getName();
   int age=db.getAge();
 }

3.使用sharedPreferences傳遞數據

4.使用類的靜態變量傳遞數據

最好的方法是使用Intent.putExtra() ,您可以在其中存儲鍵值對。 以下是如何執行此操作的簡短指南: 如何使用intent.putextra在活動之間傳遞數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM