Android RoboGuice 使用指南(2):第一个例子Hello World
首先介绍一下如果将Guice 和RoboGuice 的库添加到项目中。
下载RoboGuice和guice-2.0-no_aop.jar(not guice-3.0),或者下载
创建一个新Android项目,比如GuiceDemo,目标平台Android1.5以上。
一般可以在该项目下添加一个lib目录,将两个jar文件拷到lib目录下,然后通过: Project > Properties > Java Build Path > Libraries > Add External JARs
添加了对应guice 和roboguice库的引用之后,就可以开始编写第一个使用roboguice 的例子。
使用roboguice 的步骤:
1. 创建一个RoboApplication 的子类GuiceApplication,GuiceApplication为Appliacation的子类,因此需要修改AndroidManifest.xml,将Application 的name 指向这个类。可以参见Android简明开发教程九:创建应用程序框架
<application android:name=”GuiceApplication”android:icon=”@drawable/icon” android:label=”@string/app_name”><activity android:name=”.GuiceDemo”android:label=”@string/app_name”><intent-filter><action android:name=”android.intent.action.MAIN” /><category android:name=”android.intent.category.LAUNCHER” /></intent-filter></activity></application>
<?xml version=”1.0″ encoding=”utf-8″?><LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”android:orientation=”vertical”android:layout_width=”fill_parent”android:layout_height=”fill_parent”><TextViewandroid:id=”@+id/hello”android:layout_width=”fill_parent”android:layout_height=”wrap_content”android:text=”@string/hello”/></LinearLayout>
public class GuiceDemo extends RoboActivity { @InjectView (R.id.hello) TextView helloLabel; @Inject IGreetingService greetingServce; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); helloLabel.setText(greetingServce.getGreetings()); }}
public class HelloChina implements IGreetingService{ @Override public String getGreetings() { return "Hello,China"; } } public class HelloWorld implements IGreetingService{ @Override public String getGreetings() { return "Hello,World"; } }
public class GreetingModule extends AbstractAndroidModule{ @Overrideprotected void configure() {bind(IGreetingService.class).to(HelloWorld.class);//bind(IGreetingService.class).to(HelloChina.class); } }
public class GuiceApplication extends RoboApplication { protected void addApplicationModules(List<Module> modules) { modules.add(new GreetingModule()); } }