投稿

ラベル(Fragment)が付いた投稿を表示しています

【Android】Fragmentを使う② - ActivityとFragmentの相互呼び出し -

イメージ
前回 の記事でFragmentの簡単な実装について書きました。今回はそれの応用編です。 Fragmentに定義したメソッドをActvity側から呼び出したり、FragmentからAcitivityのメソッドを呼び出す方法をまとめます。 ActivityからFragmentのメソッドを実行する まずは親レイアウトであるMainActivity側から、それぞれのFragmentに定義してあるメソッドを実行してみます。この場合Fragment側に特別な処理は必要なく、呼び出し元のMainActivityのみで完結します。 メインのレイアウトにボタンを追加する activity_main.xml <LinearLayout android:id="@+id/llButton" android:gravity="center_horizontal" android:orientation="horizontal" android:layout_below="@id/mainText" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/buttonTest1" android:text=" Fragment 1 -> TEST " android:padding="5dp" android:layout_margin="5dp" android:textAllCaps="false" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button

【Android】Fragmentを使う① - 単純なFragmentの実装 -

イメージ
FragmentはActivityに設置するViewを機能ごとに小分けして、元来Activityに集中しがちだったロジックを細分化する方法です。 複数人で開発しているときはコンフリクトがおきにくいのでかなり便利です。 今回はFragmentの単純な例を実装してみました。 画面構成 画面の構成としてはMainActivityの下に、2つのFragmentが紐付いている状態です。 2つのFragmentはそれぞれのレイアウト構成ファイルを読み込んでいます。 実装 ライブラリの追加 app/build.gradle annotationProcessor "org.androidannotations:androidannotations:+" implementation "org.androidannotations:androidannotations-api:+" レイアウトファイル layout/fragment_main1.xml Fragment1で使用するレイアウトを定義します。 ここではTextView、EditText、Buttonの3つのViewを設置しています。 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffa" android:padding="5dp" android:orientation="vertical"> <TextView android:id=&quo