1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Fragmentで画面遷移する方法メモ

Posted at

リファレンスによれば、
FragmentはActivityの中に配置し、いろいろなことに使えるそうだ。(ざっくり)

FragmentTransactionによって追加したり削除したり、表示したり非表示にしたり、などなどできるようだ。
FragmentTransactionはFragmentManagerを使って開始&取得する。
FragmentManagerはActivityからgetFragmentManagerで取得できる。

アプリの初期化時にはaddを使ってFragmentを追加&表示する。

        MainFragment fragment = MainFragment.newInstance();
        getFragmentManager().beginTransaction().add(R.id.container, fragment).commit();

File > New > Fragmentから追加したBlankFragmentを使ってMainFragmentクラスを作成すると、
MainActivityからaddした後、OnAttach内で例外を発生する。
onFragmentInteractionというメソッドを実装していないため。
MainActivity側で上記のメソッドを実装する。

public class MainActivity extends AppCompatActivity implements MainFragment.OnFragmentInteractionListener {

    @Override
    public void onFragmentInteraction(Uri uri) {
        // ここでFragment側で起きた何かをハンドリングする
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?