Created
December 13, 2012 03:44
-
-
Save STAR-ZERO/4273846 to your computer and use it in GitHub Desktop.
【Android】Fragmentのテンプレート的なもの
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 SampleFragment extends Fragment { | |
/** Fragmentで保持しておくデータ */ | |
private int mData; | |
/** | |
* Fragmentインスタンスを生成した返却. | |
* | |
* コンストラクタに引数を渡すのはダメ。 | |
* Fragmentがメモリ不足で破棄され、そこから復帰する時に空のコンストラクタ呼ばれる。 | |
* | |
* このメソッドでsetArgumentsを使用して再生成されたときも引数が渡せるようにする。 | |
* | |
* @param index 引数 | |
* @return Fragmentインスタンス | |
*/ | |
public static SampleFragment newInstance(int index) { | |
SampleFragment fragment = new SampleFragment(); | |
// 引数を設定 | |
Bundle args = new Bundle(); | |
args.putInt("index", index); | |
fragment.setArguments(args); | |
return fragment; | |
} | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { | |
// FragmentのViewを返却 | |
return inflater.inflate(R.layout.hoge, container, false); | |
} | |
@Override | |
public void onActivityCreated(Bundle savedInstanceState) { | |
super.onActivityCreated(savedInstanceState); | |
if (savedInstanceState != null) { | |
// onSaveInstanceStateで保存されたデータを復元 | |
mData = savedInstanceState.getInt("data"); | |
} | |
// 引数を取得 | |
Bundle args = getArguments(); | |
int index = args.getInt("index"); | |
// Viewの初期化、イベントハンドラ設定など | |
Button button = (Button) getView().findViewById(R.id.btn); | |
} | |
@Override | |
public void onSaveInstanceState(Bundle outState) { | |
super.onSaveInstanceState(outState); | |
// Fragment内で残しておきたいデータを保存 | |
outState.putInt("data", mData); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment