再谈Fragment(二)

Fragment的生命周期

关键方法

onAttach()

onCreateView()


启动Fragment-->屏幕锁屏-->屏幕解锁-->切换到其他的Fragment


-->回到桌面-->回到应用-->退出Fragment



启动Fragment

onAttach()-->onCreate()-->onCreateView()-->onActivityCreated()-->onStart()-->onResume()


屏幕锁屏

onPause()-->onStop()


屏幕解锁

onStart()-->onResume()


切换到其他Fragment


第一个:onPause()-->onStop()-->onDestroyView()-->onDestroy()-->onDetach()


第二个:onAttach()-->onCreate()-->onCreateView()-->onActivityCreated()-->onStart()-->onResume()




Fragment与Activity通信


Fragment可调用getActivity()方法获取它所在的Activity

Activity可调用FragmentManager的findFragmentById()或findFragmentByTag()方法获取Fragment


Activity-->Fragment:在Activity中创建Bundle数据包,并调用Fragment的setArguments(Bundle bundle)方法

Fragment-->Activity:需要在Fragment中定义一个内部回调接口,再让包含该Fragment的Acitivity实现该回调接口。这样Fragment可调用该回调方法将数据传递给Acitivity


main4.xml




    

    


MyFragment5.java

public class MyFragment5 extends Fragment {
	
	private String code = "Thank you, Activity!";
	
	public MyListener listener;
	
	public interface MyListener {
		public void thank(String code);
	}
	
	@Override
	public void onAttach(Activity activity) {
		listener = (MyListener) activity;
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment2, container, false);
		TextView tv = (TextView) view.findViewById(R.id.text);
		String text = (String) getArguments().get("name");
		tv.setText(text);
		Toast.makeText(getActivity(), "已成功接收到" + text, Toast.LENGTH_SHORT).show();
		Toast.makeText(getActivity(), "向Activity发送" + code, Toast.LENGTH_SHORT).show();
		listener.thank(code);
		return view;
	}
	
}



MainActivity4.java

public class MainActivity4 extends Activity implements MyListener {

	private EditText editText;
	private Button send;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main4);
		editText = (EditText) findViewById(R.id.editText);
		send = (Button) findViewById(R.id.send);
		
		send.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String text = editText.getText().toString();
				MyFragment5 fragment5 = new MyFragment5();
				Bundle bundle = new Bundle();
				bundle.putString("name", text);
				fragment5.setArguments(bundle);
				FragmentManager fragmentManager = getFragmentManager();
				FragmentTransaction beginTransaction = 
						fragmentManager.beginTransaction();
				beginTransaction.add(R.id.layout, fragment5, "fragment5");
				beginTransaction.commit();
				Toast.makeText(MainActivity4.this, "向Fragment发送数据" + text, Toast.LENGTH_SHORT).show();
			}
		});
		
	}

	@Override
	public void thank(String code) {
		Toast.makeText(MainActivity4.this, "已成功接收到" + code + ", 客气了", 
				Toast.LENGTH_SHORT).show();
	}
	
}








你可能感兴趣的:(Fragment)