Fragmentを表示する方法
Fragmentを利用する場合API level > 11が必要
手順
- fragmentのレイアウト作成
- Fragmentのサブクラス作成
- Activityのレイアウトにて紐付け
詳細
fragmentのレイアウト作成します。res->layoutでレイアウト(ここではfargment_main.xml)を作成して以下を記述。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!--表示確認用のテキスト--> <TextView android:text="fragment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> </RelativeLayout>
続いてFragmentのサブクラス(ここではMainFragment)を作成して以下を記述しましょう。
public class MainFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main, container, false); } }
最後にActivityに紐付いているxml(ここではactivity_main.xml)で以下を記述して完成です。
<fragment android:name="com.sfs.crypton.myapplication.MainFragment" android:id="@+id/mainFragment" android:layout_width="match_parent" android:layout_height="match_parent"/>