要在Android中使用Dagger注入共享ViewModel到Fragment,可以按照以下步骤进行操作:
implementation 'com.google.dagger:dagger:2.x'
annotationProcessor 'com.google.dagger:dagger-compiler:2.x'
@Module
public abstract class SharedViewModelModule {
@Provides
@Singleton
static SharedViewModel provideSharedViewModel() {
return new SharedViewModel();
}
}
public class MyFragment extends Fragment {
@Inject
SharedViewModel sharedViewModel;
// ...
}
@Singleton
@Component(modules = {SharedViewModelModule.class})
public interface AppComponent {
void inject(MyFragment fragment);
// ...
}
public class MainActivity extends AppCompatActivity {
@Inject
SharedViewModel sharedViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 创建AppComponent的实例并进行注入
AppComponent appComponent = DaggerAppComponent.create();
appComponent.inject(this);
// ...
}
}
这样,当MyFragment被创建时,Dagger会自动注入SharedViewModel的实例到Fragment中的sharedViewModel字段中。注意确保在创建Fragment之前,已经进行了AppComponent的注入。
这是一个简单的示例,你可以根据自己的需求进行更复杂的注入。