一、在Activity布局文件中静态添加Fragment:

res/layout-large/news_articles.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<fragment android:name="com.example.android.fragments.HeadlinesFragment"
android:id="@+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />

<fragment android:name="com.example.android.fragments.ArticleFragment"
android:id="@+id/article_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />

</LinearLayout>


二、为Fragment指定布局文件:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;

public class ArticleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.article_view, container, false);
}
}

每个Fragment实例需要关联到一个FragmeActivity,所以要添加Fragment的自定义Activity需继承FragmentActivity;
因为FragmentActivity是定义在API 11 以后的v4 Support Library,且继承自Activity,所以在API 11+的平台上可以直接继承Activity。
如果使用的库是v7 appcompat library,应该继承AppCompatActivity,它是FragmentActivity的子类。

三.动态添加Fragment:注:Activity必须包含一个view容器,用来添加Fragment组件,如:
res/layout/news_articles.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
代码中动态添加:用到FragmentManager和FragmentTransaction类:

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);

// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {

// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}

// Create a new Fragment to be placed in the activity layout
HeadlinesFragment firstFragment = new HeadlinesFragment();

// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());

// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
}
一定要记得调用commit()方法。

四、动态替换Fragment:

// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();


五、Fragment之间通信:


注:Fragment之间的通信是通过他们关联的Activity进行的,两个Fragment之间不能直接通信
为了让一个Fragment与和它关联的Activity通信,可以在Fragment类中定义一个接口,Activity
类中实现该接口,然后Fragment在它的onAttach()生命周期方法中实例化接口,用该实例去调用
接口中的方法,实现通信,如下所示:

Fragment定义接口:

public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;

// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);

// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}

...
}
Activity实现接口:
public static class MainActivity extends Activity
implements HeadlinesFragment.OnHeadlineSelectedListener{
...

public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article
}
}
调用方法:

 @Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onArticleSelected(position);
}


六.Activity可以调用findFragmentById()方法获取关联于它的Fragment实例,然后可以调用该Fragment的public方法,如:
  ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);

七、Fragment生命周期方法:
onAttach(): 当该Fragment关联到Activity时调用,Activity作为参数传入;
oncreate(): 与Activity的oncreate()方法一样,实例化该Fragment调用;
oncreateView():创建Fragment自身布局时调用;
onActivityCreated():当与之关联的Activity的oncreate()方法返回时调用;
onStart(),onResume(),onStop(),onPause():这些方法跟Activity的生命周期方法一样;
onDestroyView():与oncreateView()方法相对应;
onDetach():当与Activity接触关联时调用,与onAttach()相对应。

只有当与之关联的Activity处于resumed状态时,Fragment的生命周期方法才可以独立的改变;
否则要受到与之关联的Activity的生命周期方法的限制。

附生命周期图:





更多相关文章

  1. android在onCreate()方法中获取View的宽度与高度的方法实战
  2. W/System.err:at java.net.PlainDatagramSocketImpl.bind(PlainDa
  3. Android Studio获取数字签名(SHA1)的方法
  4. Android Volley:使用方法总结及实例解析
  5. eclipse下运行EasyAR官方sample的方法
  6. Android App性能信息获取方法
  7. Android Studio 检测内存泄漏与解决方法
  8. C#/Java 调用WSDL接口及方法
  9. Javadoc转换chm帮助文档的四种方法总结

随机推荐

  1. 2010.12.10——— android 定位跟踪
  2. ?android:attr/属性 与 ?android:属性
  3. 【转】android manifest.xml中元素含义
  4. Android OpenGL ES学习笔记之实现OpenGL
  5. android 获取手机通讯录信息
  6. Activity背景色为透明的2种方法
  7. android activity tabhost
  8. Android软件安装文件夹
  9. Android安全问题
  10. Android——从init进程启动流程