2
3

More than 3 years have passed since last update.

[ Android ] Fragment基礎

Last updated at Posted at 2019-11-05

AndroidのFragmentについて記す。

Fragment

ライフサイクルを持ったビューのこと。
追加削除をしたり、複数の画面を使いまわすことができる。

実装方法

まずレイアウトファイル(xml)を作成する。
次にFragmentを継承したクラスを作成し、onCreateView()内で
レイアウトファイルをViewとして生成する。
具体的には以下のように書く。

public class MainFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        //作成したレイアウトファイルをViewとして作成
        return inflater.inflate(R.layout.fragment_main, container, false);
    }
}

ViewのアクションはonViewCreated()内で実装する。
onViewCreated()はView生成後に呼ばれるメソッドである。

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTextView = (TextView) view.findViewById(R.id.textView);
        Button button = (Button)view.findViewById(R.id.button).
        button.setOnClickListener((View v)-> {
                mTextView.setText(mTextView.getText() + "!");  
        });
    }

使い方

レイアウトファイルの左下「デザイン」を選択すると、fragmentがある。
TextViewやButtonと同様にドラッグすることで追加できる。
Fragmentが複数ある場合、ドラッグした際に選択できるようになっている。

参考サイト

Fragment基礎
https://qiita.com/Reyurnible/items/dffd70144da213e1208b

2
3
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
2
3