这里只是给出三个类RightFragment、LeftFragment、MainActivity中的简易代码,至于布局怎么设定,不做赘述。

思路:从碎片一获取与之依托的活动实例,碎片一可以调用活动里面的功能;在活动中获取碎片二的活动实例,活动可以使用碎片二的功能。碎片一间接调用碎片二的功能。

一、RightFragment:

package com.example.fragmenttest2;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class RightFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MainActivity activity = (MainActivity) getActivity();//获取与之依托的活动实例
LeftFragment callleft = activity.callleft();
callleft.show();//使用活动的功能,这个功能正好是调用碎片二的方法。
View view = inflater.inflate(R.layout.right_fragment, container, false);
return view;
} public void show(){
System.out.println("RightFragment");
}
}

二、MainActivity:

package com.example.fragmenttest2;

import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity implements OnClickListener { private LeftFragment leftFragment; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
Button button1 = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
button1.setOnClickListener(this); } @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button://按钮一,实现了一次替换碎片的功能
AnotherRightFragment fragment = new AnotherRightFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.right_layout, fragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case R.id.button1:
leftFragment = (LeftFragment) getFragmentManager()//按钮二,可直接使用left碎片即碎片二的功能
.findFragmentById(R.id.left_fragment);
leftFragment.show();
break;
default:
break;
} } public void show(){
System.out.println("MainActivity");
} public LeftFragment callleft(){//抽取方法,调用碎片二的功能
leftFragment = (LeftFragment) getFragmentManager()
.findFragmentById(R.id.left_fragment);
return leftFragment;
} }

三、LeftFragment:

package com.example.fragmenttest2;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class LeftFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { View view = inflater.inflate(R.layout.left_fragment, container, false);
return view;
} public void show(){//碎片二的功能,这里只为了演示知识打印一行输出
System.out.println("LeftFragment");
}
}

启动程序,发现直接打印的一行输出:

LeftFragment

这样就实现了碎片与活动,以及碎片与碎片直接的通信。

05-07 09:30