欢迎来到Doc100.Net免费学习资源知识分享平台!
您的位置:首页 > 程序异常 >

handler,registerreceiver以及activty跟broadcastreceiver的传值

更新时间: 2014-01-05 02:59:03 责任编辑: Author_N1

 

handler,registerReceiver以及activty和BroadcastReceiver的传值
public class Container extends TabActivity{

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		host = getTabHost();
		Intent intent = new Intent(this, Tab1Activity.class);
		host.addTab(host.newTabSpec("one").setIndicator("TAB1").setContent(intent));
		intent = new Intent(this, Tab2Activity.class);
		host.addTab(host.newTabSpec("two").setIndicator("TAB2").setContent(intent));
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		receiver = new TabChangeReceiver();
		registerReceiver(receiver, new IntentFilter("com.novoda.TAB"), null, mHandler);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver);
	};
	
    protected Handler mHandler = new Handler() {
        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
            	case SWITCH_TAB:
            		Log.i("handler", "using the handler");
                    host.setCurrentTab(msg.arg1);            		
            		break;
            }
        }
    };

    public class TabChangeReceiver extends android.content.BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			int intExtra = intent.getIntExtra("tab", 0);
			Log.i(TabChangeReceiver.class.getSimpleName(), "Recieved broadcast with extra=[" + intExtra + "]");
			
			mHandler.sendMessage(mHandler.obtainMessage(SWITCH_TAB, intExtra, 0));
		}
	}
	
	private TabHost host;
	public static final int SWITCH_TAB = 2545;
	protected static TabChangeReceiver receiver;
	
}

 

public class Tab1Activity extends Activity{
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.tab1);
        findViewById(R.id.tab1button).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent("com.novoda.TAB");
				intent.putExtra("tab", 1);
				sendBroadcast(intent);
			}
		});
	}
}

 

public class Tab2Activity extends Activity{
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.tab2);
        findViewById(R.id.tab2button).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent("com.novoda.TAB");
				intent.putExtra("tab", 0);
				sendBroadcast(intent);
			}
		});        
	}
}

 

这个传值是通过setbroadcast监听实现的,这个主要用来监听 同一个类型的activityIntent intent = new Intent("com.novoda.TAB");
比较好,这里呢也使用handler处理监听到的消息

上一篇:上一篇
下一篇:下一篇

 

随机推荐程序问答结果

 

 

如对文章有任何疑问请提交到问题反馈,或者您对内容不满意,请您反馈给我们DOC100.NET论坛发贴求解。
DOC100.NET资源网,机器学习分类整理更新日期::2014-01-05 02:59:03
如需转载,请注明文章出处和来源网址:http://www.doc100.net/bugs/t/16987/
本文WWW.DOC100.NET DOC100.NET版权所有。