1、使用广播
在Activity的onCreate()或者Fragment烦人onAttach()中注册广播,然后记得在onDestroy中解注册广播。这样在需要刷新的地方直接发送广播就可以了。
public class GasFragment extends Fragment {
private TextView gasName;
private TextView gasadderss;
private ReceiveBroadCast receiveBroadCast;
public GasFragment (){}
@Override
public void onAttach(Activity activity) {
/** 注册广播 */
receiveBroadCast = new ReceiveBroadCast();
IntentFilter filter = new IntentFilter();
filter.addAction("com.gasFragment"); //只有持有相同的action的接受者才能接收此广播
activity.registerReceiver(receiveBroadCast, filter);
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_gas, null);
gasName = (TextView) view.findViewById(R.id.frag_tv_gasname);
gasadderss = (TextView) view.findViewById(R.id.fraggas_tv_adderss);
}
});
return view;
}
class ReceiveBroadCast extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
//得到广播中得到的数据,并显示出来
String gasname = intent.getExtras().getString("gasName");
String address = intent.getExtras().getString("address");
gasadderss.setText("地址:\n "+address);
gasName.setText(gasname);
}
}
/**
*注销广播
* */
@Override
public void onDestroyView() {
getActivity().unregisterReceiver(receiveBroadCast);
super.onDestroyView();
}
}
2、使用Handler
首先在Activity或者Fragment中建立Handler,然后在别的activity 或者 fragment 中使用,可以将Handler做成静态的。