Last active
December 10, 2015 10:29
-
-
Save benigumocom/4421644 to your computer and use it in GitHub Desktop.
アクティビティへのイベントコールバックの作成
(フラグメントからホストアクティビティへイベントを渡す)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
フラグメントは複合的な1つのViewであると考え、内包するUIのタップイベントなどを集約し、通知するようにします。そのイベントのホストとなるアクティビティにコールバックし次の処理につなげます。