所以我正在学习MVVM,喜欢它.
但是......到目前为止我的问题如下:
使用MVVM实现谷歌地图.(我是在活动或视图模型上做的吗?我只能在活动上实现它..)
特别是CONTEXT ..可以像下面那样传递它吗?
这是我的ViewModel:
public class DashboardViewModel implements ViewModel {
public final ObservableField<String> dashButton = new ObservableField<>("");
public final Action onRandomSearch;
private Context context;
public DashboardViewModel(Context context) {
this.context = context;
onRandomSearch = () -> {
String randomString = UUID.randomUUID().toString();
String randomQuery = randomString.substring(0, 3) + " " + randomString.substring(5, 8);
dashButton.set(randomQuery); //JUST TO TEST
};
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的活动:
public class DashboardActivity extends MvvmActivity {
@NonNull
@Override
protected ViewModel createViewModel() {
loadMap();
return new DashboardViewModel(this);
}
@Override
protected int getLayoutId() {
return R.layout.activity_dashboard;
}
private void loadMap() {
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
startLocation();
...
Run Code Online (Sandbox Code Playgroud)
现在,为了让google地图处理我的应用程序,我必须实现OnMapReadyCallback,如下所示:
public class DashboardActivity extends MvvmActivity implements OnMapReadyCallback
Run Code Online (Sandbox Code Playgroud)
我需要与方法进行通信以获取当前位置,这是我在DashboardActivity中实现的.
我应该迁移逻辑以使映射在ViewModel中工作吗?
我在这里有点失落.
我在MVVM中遇到了与SupportMapFragment相同的问题.对于临时解决方案,我使用mapview而不是SupportMapFragment.
首先,您需要在CustomBinding中创建一个方法.
@BindingAdapter("initMap")
public static void initMap(final MapView mapView, final LatLng latLng) {
if (mapView != null) {
mapView.onCreate(new Bundle());
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker
googleMap.addMarker(new MarkerOptions().position(latLng).title("Marker in India"));
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
xml文件的代码
<com.google.android.gms.maps.MapView
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="200dp"
app:initMap="@{viewmodel.mMapLatLngObservable}" />
Run Code Online (Sandbox Code Playgroud)
在viewmodel类中,你必须占用一个观察者字段
public ObservableField<LatLng> mMapLatLng = new ObservableField<>();
Run Code Online (Sandbox Code Playgroud)
因此,当您在上面的观察变量(mMapLatLng)中设置当前位置时,将调用OnMapReadyCallback.
| 归档时间: |
|
| 查看次数: |
3783 次 |
| 最近记录: |