首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 開發:Intent 傳遞數據並在新 Activity 中顯示文本的標準流程

     編輯:程式設計綜合問答

問題分析

開發者在點擊按鈕後啟動新 Activity,但嘗試在當前 Activity 中通過 findViewById 獲取新 Activity 的 TextView 並設置文本,導致文本顯示在錯誤位置。根本原因是:findViewById 只能查找當前 Activity 的佈局視圖,無法跨 Activity 訪問視圖。

正確流程:Intent 攜帶數據 → 新 Activity 接收並顯示

步驟一:發送方構建 Intent 並攜帶數據

Button btnTutorial = findViewById(R.id.tutorial1);
btnTutorial.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // 1. 創建 Intent(顯式 Intent 推薦)
        Intent intent = new Intent(MainActivity.this, TutorialOneActivity.class);
        
        // 2. 構建 Bundle 攜帶數據
        Bundle bundle = new Bundle();
        bundle.putString("tutorial_text", "這是要在新 Activity 中顯示的教程文本內容");
        // 可攜帶多種類型
        // bundle.putInt("step", 1);
        // bundle.putBoolean("is_first", true);
        
        // 3. 將 Bundle 放入 Intent
        intent.putExtras(bundle);
        
        // 4. 啟動 Activity
        startActivity(intent);
    }
});

步驟二:接收方在 onCreate 中獲取數據並設置視圖

public class TutorialOneActivity extends AppCompatActivity {
    
    private TextView tvContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tutorial_one); // 設置新 Activity 的佈局
        
        // 1. 獲取當前 Activity 的視圖引用
        tvContent = findViewById(R.id.tutorial_text_view);
        
        // 2. 從 Intent 獲取數據
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                String text = bundle.getString("tutorial_text", "默認文本");
                // 3. 設置到當前 Activity 的 TextView
                tvContent.setText(text);
            }
        }
    }
}

步驟三:AndroidManifest.xml 註冊新 Activity

<activity android:name=".TutorialOneActivity" />

關鍵知識點總結

誤區正確理解
在 Activity A 中 findViewById(Activity B 的 View)跨 Activity 不可直接訪問視圖,必須通過 Intent 傳遞數據
startActivity 後立即操作新 Activity 視圖新 Activity 異步創建,只能在其 onCreate/onStart 中操作自身視圖
使用隱式 Intent "my.android.TUTORIALONE"推薦顯式 Intent new Intent(A.this, B.class),性能更好、無歧義

進階:使用 Parcelable 傳遞複雜對象

// 數據類實現 Parcelable
@Parcelize
data class TutorialData(
    val title: String,
    val content: String,
    val step: Int,
    val images: List
) : Parcelable

// 發送
intent.putExtra("tutorial_data", tutorialData)

// 接收
TutorialData data = intent.getParcelableExtra("tutorial_data");

最佳實踐建議

  • 定義 Key 常量類:public static final String KEY_TUTORIAL_TEXT = "key_tutorial_text"; 避免字符串拼寫錯誤。
  • 提供默認值:bundle.getString(KEY, "默認值") 防止 NPE。
  • 大數據傳遞(>1MB)勿用 Intent,改用 SharedPreferences、文件、ViewModel、EventBus 等。
  • 使用 ActivityResultContracts (AndroidX) 替代 startActivityForResult 獲取返回結果。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved