Android RoboGuice 使用指南(18):Inject Resources

jerry Android 2015年08月24日 收藏

Roboguice 對訪問res 目錄下各種資源drawable, arrary, string 等也提供了注入支持。可以通過@InjectResource 很方便的應用所需資源。

本例修改Android ApiDemos示例解析(48):Content->Resources->Resources 使用Inject Resource方法來訪問資源。

  1. public class InjectResourceDemo extends RoboActivity {
  2.  
  3. @InjectView (R.id.styled_text) TextView styled_text;
  4. @InjectView (R.id.plain_text) TextView plain_text;
  5. @InjectView (R.id.res1) TextView res1;
  6. @Inject Resources res;
  7. @InjectResource(R.string.styled_text) String str;
  8.  
  9.  
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.injectresource);
  14.  
  15. //Use res to get the string resources
  16. CharSequence cs=res.getText(R.string.styled_text);
  17. // Note the use of
  18. // CharSequence instead of String
  19. // so we don't lose the style info.
  20. styled_text.setText(cs);
  21.  
  22. // Use the same resource, but convert it to
  23. // a string, which causes it
  24. // to lose the style information.
  25. plain_text.setText(str);
  26. res1.setText(cs);
  27.  
  28. }
  29.  
  30. }

本例下載