<fragment
android:id="@+id/my_fragment"
android:name="com.example.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
參數傳遞方式:無法通過構造函數傳參。需在 Activity `onCreate` 中:
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.my_fragment);
Bundle args = new Bundle();
args.putString("key", "value");
fragment.setArguments(args); // Fragment 內部 getArguments() 獲取
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("id", 123);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment, "tag")
.commit();
public class MyFragment extends Fragment {
public static MyFragment newInstance(String param) {
MyFragment f = new MyFragment();
Bundle b = new Bundle();
b.putString("arg", param);
f.setArguments(b);
return f;
}
// ...
}
Android Fragment 參數傳遞,XML 靜態聲明用 setArguments,動態添加用 newInstance 工廠模式,避免構造函數傳參導致重建失敗。