LoginSignup
1
2

More than 5 years have passed since last update.

【不定期更新】Fragmentを使い始めた初心者による個人的メモ

Last updated at Posted at 2017-10-26

事の始まり

―先生、Android開発がしたいです

そんなことを述べて幕が開けた、私の大学卒業研究(開発課題実習)でしたが、私のまだ未熟な技術でAndroidアプリ開発は骨が折れる作業です。

ここでは私個人がこの開発課題実習でつまずいたFragmentに関する個人的なメモを残しています。チラシの裏のメモ書き程度にでもしてください。

なお、現在絶賛開発課題実習の真っ只中なので、内容は逐一更新されます。

開発環境

OS:Windows 10
IDE:Android Studio 2.2.3
Compiler:Java 1.8.0_144
Debugger:Nexus 9 Android 7.1.1(実機デバッグ)

FragmentをProjectに突っ込む方法

1.Android Studio上の「Project Tree」が「Android」になっていることを確認し、「app」の上で右クリックする
スクリーンショット (48).png

2.New → Fragment → Fragment(Blank) を選択し、適当な名前をつけて"Finish"する
スクリーンショット (49)_LI.jpg

Fragmentを静的にActivityに載せる

UIエディタ画面のコンポーネントパレットの
 "Layouts" → "<fragment>"を選択し、載せたいFragmentを選択する
スクリーンショット (51).png
 ※自作したFragmentのjavaソースは、独自のパッケージ名で表示されます。
  今回の場合:com.example.miqa3893.monitor_controller

何も表示されていなくても、デバッグ時に表示されるので安心。

Fragmentを動的にActivityに載せる

1.Fragmentを載せたいLayoutにIDを指定する。(ソースコードで指定する時にわかりやすくするため)

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.miqa3893.monitor_controller.MainActivity">

    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="752dp"
        android:layout_height="935dp"
        android:orientation="horizontal"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

2.Activity側のjavaソースに以下を実装

MainActivity.java
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //自作したFragmentクラス
        HomeFragment fragment = new HomeFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //addメソッド
        // 引数1:先程指定したLayoutのID
        // 引数2:自作したFragmentクラスのインスタンス
        // 引数3:Fragmentを識別するタグ(String)
        transaction.add(R.id.fragment_container,fragment,"Home").commit();   //commit()を忘れないで
    }

※先程の節で紹介した、FragmentのLayoutコンポーネントを直接入れ込むと、表示したいFragmentが二重に表示されます。

(以降は編集中です)

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