可以定义一个接口,然后在Acitivity中实现该接口,在Fragement中通过回调,将信息发送至Acitivity中
MainActivity.java:
interface CallBack {
public void call(Bundle arg);
}
public class MainActivity extends Activity implements CallBack{
Button sendButton;
String name=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChooseFragment chooseFragment=new ChooseFragment();
FragmentTransaction transaction=getFragmentManager().beginTransaction();
transaction.replace(R.id.main, chooseFragment);
}
@Override
public void call(Bundle arg) {
String s=arg.getString("name");
Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
name=s;
}
}
ChooseFragment.java
public class ChooseFragment extends Fragment {
CallBack callBack=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_choose, container, false);
Bundle bundle=new Bundle();
bundle.putString("name","hello");
callBack.call(bundle);
return view;
}
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
callBack=(MainActivity)activity;
}
}