新建activity继承fragmentactivity
在布局文件中拖入一个layout,起个名字比如fragmentlayout
新建一个class,继承fragment
新建一个layout,在里面随便放几个控件
在fragment中创建onActivityCreated,onCreateView
写如下代码
/* * (non-Javadoc) * * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle) */ @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); button1 = (Button) getView().findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(getActivity(), "ssssss", Toast.LENGTH_LONG) .show(); } }); } /* * (non-Javadoc) * * @see android.app.Fragment#onCreateView(android.view.LayoutInflater, * android.view.ViewGroup, android.os.Bundle) */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return inflater.inflate(R.layout.fragmentno1, container, false); }
然后到activity中添加如下代码
private Fragmentno1 fragmentno1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ac); fragmentno1 = new Fragmentno1(); getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, fragmentno1).commit(); }
这样就可以在activity中看到fragment的内容,我上面的代码放了一个button,并写了一个监听事件,弹出提示