通过一个Activity发出改变背景颜色的广播,另一个Activity接收广播来改变自己的背景。
效果图:
小的类似于dialog其实是一个Activity,只是这个Activity的主题样式改为了Dialog的形
式。
在Activity的标签中,有
android:theme="@android:style/Theme.Dialog"
便可将这个Activity变为dialog样式的Activity。
里面只有RadioGroup单选框,将选中的颜色发出广播。
mainactivity:
package com.example.broadcasttiaozhuan;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
private RelativeLayout layout;
private BroadcastReceiver receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int color=intent.getIntExtra("color", Color.RED);
layout.setBackgroundColor(color);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout=(RelativeLayout) findViewById(R.id.layout);
IntentFilter filter=new IntentFilter();
filter.addAction("ll");
registerReceiver(receiver, filter);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(receiver);
}
public void myclick(View V)
{
startActivity(new Intent(this,OtherActivity.class));
}
}
OtherActivity:
package com.example.broadcasttiaozhuan;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class OtherActivity extends Activity implements OnCheckedChangeListener {
private RadioGroup rg;
private int color=Color.RED;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.item);
rg=(RadioGroup) findViewById(R.id.rg);
rg.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.rb_red:
color=Color.RED;
break;
case R.id.rb_green:
color=Color.GREEN;
break;
case R.id.rb_blue:
color=Color.BLUE;
break;
default:
break;
}
Intent intent=new Intent();
intent.setAction("ll");
intent.putExtra("color", color);
sendBroadcast(intent);
}
}