您好,登錄后才能下訂單哦!
Android項目中Fragment與Activity怎么實現相互跳轉?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
Activity及Fragment之間的跳轉
直接跳轉
基本使用方法
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void jump(View view) { Intent intent = new Intent(this, VideoPlayActivity.class); intent.putExtra("video_id", "1"); startActivity(intent); } }
public class VideoPlayActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_play); Intent intent = getIntent(); } }
借助工具類
然而并沒什么卵用
public static void startActivity(Context context, Class clazz,Bundle data) { Intent intent = new Intent(context, clazz); if(data != null){ intent.putExtras(data); } context.startActivity(intent); }
推薦方案
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void jump(View view) { startActivity(VideoPlayActivity.newIntent(this, "1")); } }
public class VideoPlayActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_play); } public static Intent newIntent(Context context, String vid) { Intent intent = new Intent(context, VideoPlayActivity.class); intent.putExtra("video_id", vid); return intent; } }
Fragment跳轉
public class MainFragment{ public MainFragment() { // Required empty public constructor } public static MainFragment newInstance(int pos) { MainFragment fragment = new MainFragment(); Bundle args = new Bundle(); args.putInt("pos", pos); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { pos = getArguments().getInt("pos"); } } }
看完上述內容,你們掌握Android項目中Fragment與Activity怎么實現相互跳轉的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。