研究了一上午的在Fragment获取广播,然后在网上查了一些资料,结果还是没有实现接受到广播,但最后终于看到一篇帖子是可以实现的,就转载过来了。
内容如下:
在开发中有时候会遇见一些的情况:根据不同的需求切换不同的fragment ,然后一些操作使当前fragment中显示的内容进行一些调整。很多时候我们都是想的在fragment添加到Activity中时通过 fragmet. getView()获取fragment对象的View 。然后用findViewById()获取到fragment中的控件对象进行操作,很悲剧的是不管用啊有木有。我是个小白,研究了近一周都没搞定,只有采用另一种方式对fragment中的控件进行操作了。那就是广播。 UI中需要时发送一条广播 可顺便传入一些需要的值,在fragment中接收广播,获取值并对fragment中的控件进行操作,经本人验证完全可以。以下是Demo关键代码 (顺便说一句 在fragment中 在继承销毁的方法中 要取消掉广播不然会报错)
内容如下:
在开发中有时候会遇见一些的情况:根据不同的需求切换不同的fragment ,然后一些操作使当前fragment中显示的内容进行一些调整。很多时候我们都是想的在fragment添加到Activity中时通过 fragmet. getView()获取fragment对象的View 。然后用findViewById()获取到fragment中的控件对象进行操作,很悲剧的是不管用啊有木有。我是个小白,研究了近一周都没搞定,只有采用另一种方式对fragment中的控件进行操作了。那就是广播。 UI中需要时发送一条广播 可顺便传入一些需要的值,在fragment中接收广播,获取值并对fragment中的控件进行操作,经本人验证完全可以。以下是Demo关键代码 (顺便说一句 在fragment中 在继承销毁的方法中 要取消掉广播不然会报错)
在Fragment中
-
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();
-
}
-
- }
-
public class MainPage extends FragmentActivity {
-
-
private GasFragment gasFragment; //加油站的fragment
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
-
setContentView(R.layout.main_page);
-
gasFragment = new GasFragment();
-
FragmentManager fm = getSupportFragmentManager();
-
FragmentTransaction ft = fm.beginTransaction();
-
ft.replace(R.id.main_fl_fragment, couponFragment);// 将帧布局替换成Fragment
-
ft.commit();// 提交
-
-
Intent intent = new Intent(); // Itent就是我们要发送的内容
-
intent.setAction("com.gasFragment"); // 设置你这个广播的action
-
intent.putExtra("gasName","核反应能量加油站");
-
intent.putExtra("address", "太平洋街11号");
-
sendBroadcast(intent); // 发送广播
-
}
- }