Android RoboGuice使用指南(17):Inject Extra
使用Intent 启动一个Activity,Service等时,可以通过putExtra 传送数据,被触发的Activity,Service可以使用getIntent()的getExtras 取的Extra的Bundle ,然后再根据Extra的键值(Key)取的对应的参数值。
RoboGuice提供了一个简洁的方法来取得 这些Extra 值,通过@InjectExtra 标记。
本例使用两个Activity,InjectExtraDemo 用来触发InjectExtraReceiver,在InjectExtraDemo中创建Intent时,通过putExtra 放置两个参数Extra1,Extra2.
[java] public class InjectExtraDemo extends RoboActivity {
@InjectView (R.id.button) Button button;
@Inject Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.injectextra);
button.setOnClickListener(mGoListener);
}
private OnClickListener mGoListener = new OnClickListener()
{
public void onClick(View v)
{
Intent di = new Intent();
di.setClass(context, InjectExtraReceiver.class) ;
di.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
di.putExtra("Extra1","Message1");
di.putExtra("Extra2","Message2");
context.startActivity(di);
}
};
}
public class InjectExtraDemo extends RoboActivity {
@InjectView (R.id.button) Button button;
@Inject Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.injectextra);
button.setOnClickListener(mGoListener);
}
private OnClickListener mGoListener = new OnClickListener()
{
public void onClick(View v)
{
Intent di = new Intent();
di.setClass(context, InjectExtraReceiver.class) ;
di.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
di.putExtra("Extra1","Message1");
di.putExtra("Extra2","Message2");
context.startActivity(di);
}
};
}
在InjectExtraReceiver 通过@InjectExtra 标记 ,Roboguice自动为这些变量注入由Intent传入的值,Optional=true表示该Extra为可选,如果传入的Intent不含这个Extra时,值为null.
[java] public class InjectExtraReceiver extends RoboActivity{
@InjectView (R.id.textview) TextView textView;
@InjectExtra ("Extra1" ) String extra1;
@InjectExtra ("Extra2" ) String extra2;
@InjectExtra (value="Extra3" , optional=true) String extra3;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.injectextrareceiver);
textView.setText("Extra1:"+extra1
+"\r\nExtra2:"+extra2
+"\r\nExtra3:"+extra3);
}
}
本例下载:/2012/0507/20120507110758371.zip
摘自 引路蜂移动软件
补充:移动开发 , Android ,