好吧。简单地说。Fragment和Activity的通讯可以用到接口来实现。
在Fragment类中的点击事件中加入接口方法,然后在Activity中实现接口就可以了。
需要注意的一点就是Fragment类里面的接口。需要在 public void onAttach(Activity activity)中初始化。下面放上随便写写的代码。
这是布局,一个静态的Fragment,一个动态Fragment,Fragment布局就不放了。静态的里面有3个button,动态的有2个。都只有一个TextView而已
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<fragment
android:id="@+id/fg_title"
android:name="com.example.pictureshake.F_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="@+id/fg_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/fg_title"/>
</RelativeLayout>
public class F_title extends Fragment {
Button btn, btn2, btn3;
changeFragmet cf;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
cf = (changeFragmet) activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.f1, container, false);
btn = (Button) view.findViewById(R.id.btn1);
btn2 = (Button) view.findViewById(R.id.btn2);
btn3 = (Button) view.findViewById(R.id.btn3);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "~~~~~~~~~~~~~~~~~",
Toast.LENGTH_SHORT).show();
cf.change(1);
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "~~~~~~~~~~~~~~~~~",
Toast.LENGTH_SHORT).show();
}
});
btn3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "~~~~~~~~~~~~~~~~~",
Toast.LENGTH_SHORT).show();
}
});
return view;
}
public interface changeFragmet{
void change(int index);
}
}
注意看接口就好。其他都没啥的
接下来就是主Activity的代码
public class FragmentTest extends Activity implements changeFragmet {
F_content fc;
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
fc = new F_content();
DefaultFragment();
}
@Override
public void change(int index) {
if (index == 1) {
F_config ff = new F_config();
ft = fm.beginTransaction();
ft.replace(R.id.fg_content, new F_config());
ft.commit();
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
void DefaultFragment() {
ft.add(R.id.fg_content, fc);
ft.commit();
}
}
要注意一点。每次commit之前。都需要重新赋值一个FragmentTransaction!!!!
好了就这么多,