Fragment 和 Fragment 之間的通訊
Fragment 的存在必須要要依附於Activity,FragmentActivity是繼承Activity的。Fragment和Fragment之間的通訊的橋樑就是這個FragmentManager這個類,這個類是用來管理所有的這個Fragment的,所以我們能找到任何一個你所需要的Fragment類。所以,只要在提供一個公共方法,那麼就可以在其他的Fragment中找到你需要的Fragment直接調用方法(這樣就相當與對象直接調用方法而已,只是我們沒有去new的形式而已),如下面的代碼。
需要在LeftFragement中修改RightFragment中的TextView的值。
public class RightFragment extends Fragment{
private TextView textView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_right, null);
textView = (TextView)view.findViewById(R.id.tv_change);
return view;
}
public void changeText(String str){
textView.setText(str);
}
}
public class LeftFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_left, null);
Button btn = (Button) view.findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
RightFragment rightFragment = (RightFragment) fm.findFragmentById(R.id.fragment_text); rightFragment.changeText("已經被改變....");
}
});
return view;
}
}
佈局文件:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="horizontal" >
android:name="com.stu.fragment.LeftFragment"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="fill_parent"/>
android:id="@+id/fragment_text"
android:name="com.stu.fragment.RightFragment"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="fill_parent"/>
轉自:http://blog.sina.com.cn/s/blog_aba86c0d0101fux8.html
補充:此方法通過測試,出現空指針異常。未找到原因,後改用Handler實現Fragment間通信。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.