美文网首页
在Activity中控制另一个Activity的UI更新之广播

在Activity中控制另一个Activity的UI更新之广播

作者: Rambo_Y | 来源:发表于2018-04-10 14:18 被阅读0次

在MainAcitivity中,通过广播传值,点击按钮2改变按钮1的名称。

public class MainActivity extends AppCompatActivity {
    private Button  button1;
    private Button button2;
//广播action
    public static final String action = "jason.broadcast.action";
    private ButtonReceiver receiver;
    private String textLine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button2 =(Button)findViewById(R.id.button_2);
        button1 =(Button)findViewById(R.id.button_1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(MainActivity.this,Main2Activity.class);
                startActivity(intent1);
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //传值发送广播
                Intent intent = new Intent(action);
                intent.putExtra("textLine", "text");
                sendBroadcast(intent);
            }
        });
            //接收广播
        receiver = new ButtonReceiver();
        IntentFilter intentFilter = new IntentFilter("jason.broadcast.action");
        registerReceiver(receiver, intentFilter);
    }
    //广播接收器方法
    public class ButtonReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
                //取值
            String textLine = intent.getExtras().getString("textLine");
            button1.setText(textLine);
            Toast.makeText(context,textLine,Toast.LENGTH_SHORT).show();
        }

    }

  

    //销毁广播
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

相关文章

网友评论

      本文标题:在Activity中控制另一个Activity的UI更新之广播

      本文链接:https://www.haomeiwen.com/subject/djxnhftx.html