您的位置:首页 > 产品设计 > UI/UE

利用Fragment创建动态UI 之 Fragment之间的通信

2013-07-03 11:55 399 查看
为了可以复用一个fragment,所以在定义fragment的时候,要把它定义为一个完全独立和模块化,它有它自己的layout和行为。当你定义好了这些可复用的fragment,可以把他们和activity相关联,在应用的逻辑基础上把这些fragment相互关联,从而组成一个完整的UI。

很多时候,我们需要fragment直接进行通信,比方说,根据用户的动作交换内容。所有的fragment直接的通信,都是利用与之关联的activity.2个fragment永远不可能直接通信。

定义接口

要允许fragment和它所在的activity通信,你可以在Fragment类里面定义一个接口,然后在activity里面实现这个接口。Fragment会在它的生命周期函数:onAttach()期间捕获这个接口的实现。然后就可以调用这个接口的方法和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

ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);

if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...

// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// Otherwise, we're in the one-pane layout and must swap frags...

// Create fragment and give it an argument for the selected article
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();
}
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: