Here is an example of how you could implement the MVVM (Model-View-ViewModel) architecture pattern in an Android app using Java:
- Create a
View
class, for exampleMainActivity
that extendsAppCompatActivity
and is responsible for handling user interactions and displaying data to the user.
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private MainViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(MainViewModel.class);
binding.setViewModel(viewModel);
binding.setLifecycleOwner(this);
}
}
- Create a
ViewModel
class, for exampleMainViewModel
that extendsAndroidViewModel
and is responsible for holding and processing the data for theView
, as well as handling any business logicy code
public class MainViewModel extends AndroidViewModel {
private MutableLiveData<String> data = new MutableLiveData<>();
private MainModel model;
public MainViewModel(@NonNull Application application) {
super(application);
model = new MainModel();
}
public MutableLiveData<String> getData() {
return data;
}
public void onButtonClick() {
data.setValue(model.getData());
}
}
); } }
- Create a
Model
class, for exampleMainModel
that holds the data for the app and provides methods for retrieving and updating the data
public class MainModel {
public String getData() {
return "Hello from the Model!";
}
}
- In the
activity_main.xml
layout file, use data binding to bind the UI elements to properties on theViewModel
.
<layout>
<data>
<variable
name="viewModel"
type="com.example.myapp.MainViewModel" />
</data>
<LinearLayout>
<Button
android:text="Click me"
android:onClick="@{() -> viewModel.onButtonClick()}" />
<TextView
android:text="@{viewModel.data}" />
</LinearLayout>
</layout>
<layout>
<data>
<variabl
- In the
ViewModel
, use theMutableLiveData
class to hold the data that is displayed in theView
, and useObserver
objects to update theView
when the data changes.
public class MainViewModel extends AndroidViewModel {
private MutableLiveData<String> data = new MutableLiveData<>();
private MainModel model;
public MainViewModel(@NonNull Application application) {
super(application);
model = new MainModel();
}
public MutableLiveData<String> getData() {
return data;
}
public void onButtonClick() {
data.setValue(model.getData());
}
}
} }
Comments
Post a Comment