Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active December 10, 2015 10:29
Show Gist options
  • Save benigumocom/4421644 to your computer and use it in GitHub Desktop.
Save benigumocom/4421644 to your computer and use it in GitHub Desktop.
アクティビティへのイベントコールバックの作成 (フラグメントからホストアクティビティへイベントを渡す)
public class MainActivity extends Activity
implements FragmentA.OnArtcleListener {
// コールバックを受け取るインターフェース
@Override
public void onArticleSelected(Uri articleUri) {
// 受け取ったUriで、別のView(フラグメント)を操作する
// ...
}
}
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
// コンテナのアクティビティはこのインターフェイスを実装する必要がある
public interface OnArticleSelectedListener {
public void onArticleSelected(Uri articleUri);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// クリックされたアイテムの行 ID をコンテンツプロバイダの Uri に付加する
Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);
// イベントと Uri をホストのアクティビティに送信する
mListener.onArticleSelected(noteUri);
}
}
// 1.1 フラグメント - ソフトウェア技術ドキュメントを勝手に翻訳
// https://sites.google.com/a/techdoctranslator.com/jp/android/guide/activities/fragments
@benigumocom
Copy link
Author

フラグメントは複合的な1つのViewであると考え、内包するUIのタップイベントなどを集約し、通知するようにします。そのイベントのホストとなるアクティビティにコールバックし次の処理につなげます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment