Fragment继承类的简单解析

本文介绍Android中使用Fragment实现的一种类似抽屉的导航效果。通过MainActivity的静态内部类PlaceholderFragment来根据不同section显示不同的文本提示。文章详细展示了如何通过设置参数并在onCreateView方法中获取这些参数来更新Fragment的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值