public class MyFrament extends Fragment {
<span style="color:#33CC00;"> /**
* 定义回调接口 与activity进行数 据交互
*/ </span>
public interface CallBackLenstener {
public void onChange();
}
@Override
public void onAttach(Activity activity) {
//<span style="color:#33CC00;">在onAttach把activity的数据传进fragment </span>
// Bundle args = getArguments();
// if (null != args) {
// /* // * 在这里我们可以将从Acivity收到的数据保存起来,并且显示到Fragment当中。
// */ //
// }
try {
cb = (CallBackLenstener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.to
String() + " must implement OnButtonClickListener");
}
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.frament_item, container, false);
tv = (TextView) v.findViewById(R.id.fra_item);
Button btn = (Button) v.findViewById(R.id.btn_frm);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(cb!=null){
cb.onChange();
}
}
});
tv.setTag("0x123");
return v;
}
}
<span style="color:#33FF33;">//activity类</span>
public class DbActivity extends FragmentActivity implements MyFrament.CallBackLenstener {
private MyFrament mf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db);
ViewUtils.inject(this);
mf = new MyFrament();
add();
}
public void add(){
Bundle args = new Bundle();
args.putString("hello", "Hello Fragment1");
fragment1.setArguments(args);
Log.i(TAG, "create Fragment1");
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.add(R.id.fra, mf);
transaction.addToBackStack(null);
transaction.commit();
}
@Override
public void onChange() {
<span style="color:#33CC00;"> //执行回调接口把进行数据交互
// TODO Auto-generated method stub
//得到当前fragment所在activity的实例,再通过实例找到UI </span>
TextView tv1 = (TextView) mf.getActivity().findViewById(R.id.fra_item);
tv1.setText(data.getText().toString());
}
}