今天在使用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的内容
}
}