現在我要做個Fragment與Fragment之間的通信小demo。
- 建立兩個Fragment,然後各添加1個按鈕和1個TextView。
- 單擊Fragment1的按鈕修改Fragment2裏的TextView文本。
- 相同的,單擊Fragment2裏面的按鈕修改Fragment1的TextView文本。
前期準備:在Activity裏面放進兩個fragment: 1和2,再爲其各綁定View。
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, null);
return rootView;
}
}
運行是這樣的:
爲兩個xml文件都添加TextView和Button
接下來就要去找到按鈕響應事件,在Fragment1和Fragment2的java文件中寫:
Fragment1
public class Fragment1 extends Fragment {
private TextView tv1;
private Button button1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, null);
button1 = (Button) rootView.findViewById(R.id.button1);//按鈕
tv1 = (TextView) rootView.findViewById(R.id.textView1);//文本
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("在Fragment1響應點擊按鈕事件");
//得到當前Fragment所掛載的Activity,然後得到fragment2.
Fragment2 fragment2 = (Fragment2) getActivity().getFragmentManager().findFragmentById(R.id.fragment2);
fragment2.setText("內容變化了.....");
}
});
return rootView;
}
public void setText(String text) {//定義個修改文本內容的方法
tv1.setText(text);
}
}
Fragment2
public class Fragment2 extends Fragment {
private TextView tv2;
private Button button2;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment2, null);
button2 = (Button) rootView.findViewById(R.id.button2);//按鈕
tv2 = (TextView) rootView.findViewById(R.id.textView2);//文本
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("在Fragment2響應點擊按鈕事件");
Fragment1 fragment1 = (Fragment1) getActivity().getFragmentManager().findFragmentById(R.id.fragment1);
//得到當前Fragment所掛載的Activity,然後得到fragment1.
fragment1.setText("內容變化了.....");
}
});
return rootView;
}
public void setText(String text) {
tv2.setText(text);
}
}
來看看模擬器
單擊 按鈕1:
單擊 按鈕2:
這是我在Fragment學習的一個小小的練習。請原諒我的亂碼,這個問題我也花了時間去弄,暫時還沒有找到問題所在,如果有大神知道可以評論教教我!感謝萬分!