今天在使用Android4.4 SDK新建工程發現Android有個神奇的隱藏功能,Fragment實現的類抽屜效果:
Fragment的簡單文本提示內容。PlaceholderFragment是MainActivity的一個靜態內部類,在Fragment被切換的時候,改變Fragment的提示內容。
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {//sectionNumber代表哪個section被點擊
PlaceholderFragment fragment = new PlaceholderFragment();//我一直覺得類引用自身是一種神奇的寫法
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);//鑄就神奇的關鍵實現,歸功Fragment的完美實現
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);//使用LayoutInflater,其實可以自由擴展Fragment的View內容
TextView textView = (TextView) rootView
.findViewById(R.id.section_label);
textView.setText("大家好,我是第" + Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)) + "區");
return rootView;//這裏使用layout佈局文件,只擴展了簡單的問題展示信息
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));//不知的onAttach在什麼時間被調用,但是onSectionAttached //是自定義方法,改變ActionBar的title的內容
}
}