/var/log/messages

Jun 12, 2015 - 1 minute read - Comments - android

Activity と Fragment の情報のやりとりについて

なんか妙な場所で情報取り纏めて発信したりしたので備忘までこちらにも。

はじめに

ここでは Fragment から Activity に何かをするケースに限定して実装に関する情報を控えることとします。

Fragment 側の実装について

以下の実装が必要。

  • インターフェースの定義
  • onAttach において activity オブジェクトの捕捉

Fragment が add (または replace) された時点で onAttach というメソッドが呼び出されます。以下のような interface を Fragment 側で用意しておき

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(int id);
}

onAttach において以下な手続きで activity オブジェクトを保存します。

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

Activity 側の実装について

Fragment で定義された interface を Activity に実装させます。

public class MainActivity extends ActionBarActivity 
    implements BlankFragment.OnFragmentInteractionListener {

メソッドも実装します。

@Override
public void onFragmentInteraction(int id) {
    mAdapter.remove(searchFragment(id));
    if (mAdapter.getCount() == 0) {
        mDisplayingDefault = true;
        mAdapter.add("no data", BlankFragment.newInstance(0));
    }
    mAdapter.notifyDataSetChanged();
}

Fragment 側から callback

必要な時に Fragment の側から Activity に情報を渡す事が可能となります。以下はボタンクリック契機で情報を渡す例です。

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onFragmentInteraction(mParam1);
            }
        });

onShowFileChooser (2) 土曜カレー

comments powered by Disqus