源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

使用Broadcast实现Android组件间的通信

  • 时间:2022-04-28 23:00 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:使用Broadcast实现Android组件间的通信
Android组件之间的通信有多种实现方式,Broadcast就是其中一种。在activity和fragment之间的通信,broadcast用的更多本文以一个activity为例。 效果如图: [img]http://files.jb51.net/file_images/article/201606/201668111128450.gif?201658111145[/img] 布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

  <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

  <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_marginLeft="27dp"
    android:layout_marginTop="26dp"
    android:text="发送广播" />

</LinearLayout>

MainActivity.java
public class MainActivity extends Activity {

  private Button btn;
  private TextView tv;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) this.findViewById(R.id.textView1);

    //接收广播
    LocalBroadcastManager broadcastManager = LocalBroadcastManager
        .getInstance(MainActivity.this);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.example.test1");
    BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        tv.setText("1111");
      }
    };
    broadcastManager.registerReceiver(mItemViewListClickReceiver,
        intentFilter);

    btn = (Button) this.findViewById(R.id.button1);
    btn.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {

        //发送广播
        Intent intent = new Intent("com.example.test1");
        LocalBroadcastManager.getInstance(MainActivity.this)
            .sendBroadcast(intent);
      }
    });
  }
}
原文链接:[url=http://blog.csdn.net/u012702547/article/details/46816331]http://blog.csdn.net/u012702547/article/details/46816331[/url] 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部