簡體   English   中英

如何將字符串從一個活動發送到另一個活動?

[英]How to send string from one activity to another?

我在activity2中有一個字符串

String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s", lat, lng); 

我想將此字符串插入到活動 1 的文本字段中。 我怎樣才能做到這一點?

您可以使用意圖,即活動之間發送的消息。 在 Intent 中,您可以將所有類型的數據、String、int 等放入。

在你的情況下,在activity2 ,睡前activity1 ,你將存儲一個字符串這樣的留言:

Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);

activity1onCreate() ,您可以通過檢索Bundle (包含調用活動發送的所有消息)並在其上調用getString()來獲取String消息:

Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");

然后你可以在TextView設置文本:

TextView txtView = (TextView) findViewById(R.id.your_resource_textview);    
txtView.setText(message);

希望這可以幫助 !

您可以使用Intent將數據從一個活動發送到另一個活動

Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);

然后,您可以在第二個活動中通過獲取意圖並提取額外的字符串來檢索此信息。 在您的onCreate()方法中執行此操作。

Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);

然后您所要做的就是在TextView上調用 setText 並使用該字符串。

兩種情況

當我們談論在活動之間傳遞數據時,有兩種可能的情況。

假設有兩個活動 A 和 B,並且有一個字符串 X。而您在活動 A 中

現在讓我們看看這兩種情況

  1. A-------->B
  2. A<--------B

情況1:
字符串 X 在 A 中,您想在活動 B 中獲取它。

這是非常簡單的。

在活動 A 中。

1) 創建意圖
2) 投入額外的價值
3)開始活動

Intent i = new Intent(A.this, B.class);
i.putExtra("Your_KEY",X);
startActivity(i)

在活動 B

onCreate()方法中,使用您在存儲 X (Your_KEY) 時使用的密鑰檢索字符串 X。

Intent i = getIntent();
String s = i.getStringExtra("Your_KEY");

案例2:
如果您不熟悉 Android 開發,這種情況就有點棘手 因為您在活動 A 中,您移動到活動 B,收集字符串,移回活動 A 並檢索收集的字符串或數據。 讓我們看看如何處理這種情況。

在活動 A
1) 創建意圖
2) 使用請求代碼啟動活動。

Intent i = new Intent(A.this, B.class);
startActivityForResult(i,your_req_code);

在活動 B
1) 將字符串 X 放入意圖中
2) 設置結果
3) 完成活動

Intent returnIntent = new Intent();
returnIntent .putString("KEY",X);
setResult(resCode,returnIntent);   // for the first argument, you could set Activity.RESULT_OK or your custom rescode too
finish();

再次在活動 A
1) 重寫 onActivityResult 方法

onActivityResult(int req_code, int res_code, Intent data)
{
       if(req_code==your_req_code)
       {
          String X = data.getStringExtra("KEY")
       }
}

進一步理解案例2

你可能想知道onActivityResult(int reqCode, resCode, Intent data)的 reqCode, resCode 是什么

當您必須確定從哪個活動獲得結果時, reqCode很有用。

假設您有兩個按鈕,一個按鈕啟動相機(您單擊照片並在您的活動中獲取該圖像的位圖),另一個按鈕啟動 GoogleMap(結果您返回當前位置的坐標)。 因此,為了區分這兩個活動的結果,您可以使用不同的請求代碼啟動 CameraActivty 和 MapActivity。

resCode :當您必須區分結果如何返回到請求活動時很有用。

例如:您啟動相機活動。 當相機活動開始時,您可以拍照或直接返回請求活動,而無需按下后退按鈕拍照。 因此,在這兩種情況下,您的相機活動分別發送具有不同 resCode ACTIVITY.RESULT_OK 和 ACTIVITY.RESULT_CANCEL 的結果。

相關鏈接

閱讀更多關於獲得結果

假設你的 MainActivity 中有 EditText et1,你想把它傳遞給 SecondActivity

String s=et1.getText().toString();
Bundle basket= new Bundle();
basket.putString("abc", s);
Intent a=new Intent(MainActivity.this,SecondActivity.class);
a.putExtras(basket);
startActivity(a);

現在在第二個活動中,說你想把從 EditText et1 傳遞到第二個活動的 TextView txt1 的字符串

Bundle gt=getIntent().getExtras();
str=gt.getString("abc");
txt1.setText(str);
 Intent intent = new Intent(activity1.this, activity2.class);
 intent.putExtra("message", message);
 startActivity(intent);

在activity2的onCreate()中,您可以通過檢索Bundle(其中包含調用活動發送的所有消息)並在其上調用getString()來獲取String消息:

  Bundle bundle = getIntent().getExtras();
  String message = bundle.getString("message");

意圖是強烈的

意圖對於在 android 框架中傳遞數據很有用。 您可以與您自己的Activities甚至其他流程進行通信。 檢查開發人員指南,如果您有具體問題(需要提前消化很多),請回來。

您可以使用 GNLauncher,它是我在需要與 Activity 進行大量交互的情況下編寫的實用程序庫的一部分。 使用該庫,幾乎就像使用所需參數調用 Activity 對象上的函數一樣簡單。 https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher

為了將activity2 中的文本插入到activity1 中,您首先需要在activity2 中創建一個訪問函數。

public void visitactivity1()
{
    Intent i = new Intent(this, activity1.class);
    i.putExtra("key", message);
    startActivity(i);
}

創建此函數后,您需要從activity2 的onCreate()函數調用它:

visitactivity1();

接下來,轉到activity1 Java 文件。 在其onCreate()函數中,創建一個Bundle對象,通過該對象通過其鍵獲取先前的消息,並將其存儲在一個字符串中。

    Bundle b = getIntent().getExtras();
    String message = b.getString("key", ""); // the blank String in the second parameter is the default value of this variable. In case the value from previous activity fails to be obtained, the app won't crash: instead, it'll go with the default value of an empty string

現在將此元素放在 TextView 或 EditText 中,或者使用setText()函數您喜歡的任何布局元素中。

對於那些使用Kotlin人,請改為這樣做:

  1. 使用包含字符串對象的參數創建一個方法。
  2. 導航到另一個活動

例如,


// * The Method I Mentioned Above 
private fun parseTheValue(@NonNull valueYouWantToParse: String)
{
     val intent = Intent(this, AnotherActivity::class.java)
     intent.putExtra("value", valueYouWantToParse)
     intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
     startActivity(intent)
     this.finish()
}

然后只需調用parseTheValue("the String that you want to parse")

例如,

val theValue: String
 parseTheValue(theValue)

然后在其他活動中,

val value: Bundle = intent.extras!!
// * enter the `name` from the `@param`
val str: String = value.getString("value").toString()

// * For testing
println(str)

希望這有幫助,快樂編碼!

~ John Melody 添加的 Kotlin 代碼~

所以我這樣做了,但我的輸出很奇怪,這是第一個活動

        up = findViewById(R.id.button);
        up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, updatestudents.class);
                intent.putExtra("updating",updating);
                startActivity(intent);
            }
        });

這是第二個活動

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            Current_Value = getIntent().getStringExtra("updating");
        }
        u = findViewById(R.id.text);
        u.setText("updating " + Current_Value);

在這里,我在第二個活動中檢索字符串

這是我的輸出在這里輸入圖像描述

暫無
暫無

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

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