一江场、Model層
接口:
public interface IDataManager {
String getMyLocation();
}
實(shí)現(xiàn):
public class DataManager implements IDataManager {
@Override
public String getMyLocation() {
return "北京";
}
}
二、數(shù)據(jù)類
//Location
public class Location extends BaseObservable {
@Bindable
private String location;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
notifyPropertyChanged(com.tomorrow.mvvmtest.BR.location);
}
}
三、View層
布局文件:
//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="location"
type="com.tomorrow.mvvmtest.viewmodel.Location" />
<variable
name="locationViewModel"
type="com.tomorrow.mvvmtest.viewmodel.LocationViewModel"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/main_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="30sp"
android:text="@{location.location}" /> //數(shù)據(jù)綁定
<Button
android:id="@+id/main_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@id/main_tv"
android:layout_marginTop="10dp"
android:textAllCaps="false"
android:textSize="20sp"
android:text="Get My Location"
android:onClick="@{locationViewModel.getMyLocation}"/> //事件綁定
</RelativeLayout>
</layout>
Activity:
//MainActivity
public class MainActivity extends Activity {
private ILocationViewModel mLocationViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mLocationViewModel = new LocationViewModel(binding);
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocationViewModel.onDestroy();
mLocationViewModel = null;
}
}
三谒主、ViewModel層
ViewModel接口:
//ILocationViewModel
public interface ILocationViewModel {
void onDestroy();
}
ViewModel實(shí)現(xiàn):
//LocationViewModel
public class LocationViewModel implements ILocationViewModel{
private ActivityMainBinding mBinding;
private Location mLocation;
private IDataManager mDataManager;
public LocationViewModel(ActivityMainBinding binding) {
mBinding = binding;
mDataManager = new DataManager();
initBinding();
}
private void initBinding() {
//數(shù)據(jù)綁定
mLocation = new Location();
mLocation.setLocation("My Location");
mBinding.setLocation(mLocation);
//事件綁定
mBinding.setLocationViewModel(this);
}
//事件綁定響應(yīng)方法
public void getMyLocation(View view) {
String location = mDataManager.getMyLocation();
//更新數(shù)據(jù)掉盅,同時(shí)會(huì)自動(dòng)更新界面
mLocation.setLocation(location);
}
@Override
public void onDestroy() {
mBinding = null;
mLocation = null;
mDataManager = null;
}
}