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

Android Fragment 跳轉錯誤:Intent 目標必須是 Activity,Fragment 需用 FragmentTransaction

     編輯:程式設計疑難解答

錯誤程式碼

Intent intent = new Intent(getActivity(), FragmentTarget.class); // 錯誤!
startActivity(intent);

錯誤訊息:FragmentTarget cannot be cast to Activity。

原因

Intent 只能啟動 Activity、Service、BroadcastReceiver。Fragment 不是獨立組件,必須依附於 Activity,無法直接用 Intent 啟動。

兩種正確做法

方案一:用 Activity 承載 Fragment (傳統)

  1. 建立 TargetActivity,在 onCreate 中載入 FragmentTarget。
  2. Intent intent = new Intent(getActivity(), TargetActivity.class);

方案二:Fragment 之間切換 (推薦,單 Activity 架構)

// 在 FragmentRecord 中
FragmentTarget targetFragment = new FragmentTarget();
// 可透過 Bundle 傳參
Bundle args = new Bundle();
args.putString("key", "value");
targetFragment.setArguments(args);

getFragmentManager().beginTransaction()
    .replace(R.id.fragment_container, targetFragment) // 容器 ID
    .addToBackStack(null) // 可選:支援返回鍵回上一 Fragment
    .commit();

R.id.fragment_container 是主 Activity 布局中的 FrameLayout 或 FragmentContainerView。

補充:Fragment 傳值最佳實踐

  • Fragment → Fragment:`setArguments(Bundle)` + `getArguments()`。
  • Fragment → Activity:定義介面回呼,Activity 實作介面。
  • Activity → Fragment:`findFragmentById` 取得實例呼叫 public 方法,或 `setArguments` 後重建。

總結

Fragment 不能用 Intent 跳轉。單 Activity 多 Fragment 架構下,請用 FragmentManager + FragmentTransaction 進行 replace/add,並善用 Back Stack 處理返回邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved