前回はタブレット用の大画面にフラグメントを静的に配置しましたが、
今回はスマホ用に動的に画面切替えをさせる話です。
まず、スマホ用レイアウトファイルを作成
res/layout/news_articles.xmlidに fragment_container を指定
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
次に、onCreate() のタイミングでフラグメントを作成します。
この時、 FragmentManager を使用します。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
スマホ用のレイアウトかチェック
if (findViewById(R.id.fragment_container) != null) {
再起動チェック
if (savedInstanceState != null) {
return;
}
ニュース項目のフラグメント作成
HeadlinesFragment firstFragment = new HeadlinesFragment();
アクティビティの情報を取得してセット
firstFragment.setArguments(getIntent().getExtras());
フラグメントマネージャーからトランザクションを取得
getSupportFragmentManager().beginTransaction().add(
フラグメントを指定してコミット
R.id.fragment_container, firstFragment).commit();
}
}
トランザクションを使用してadd() しているのは
「戻る」などのユーザー操作に対応する為です。
そして、画面切り替えのタイミングでトランザクションに
フラグメントを置換させます。
ニュース内容のフラグメントを作成
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
どのニュースを選んでいるかをセット
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
フラグメントの置換
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
準備できたらコミット
transaction.commit();
えー前回と今回で断片的な解説ですが(フラグメントだけに)

次回で全体像がわかると思います。では。