安卓mvvm框架helloworld
时间: 2023-11-13 15:02:50 浏览: 104
安卓MVVM框架的HelloWorld可以通过以下步骤实现:
1. 在build.gradle文件中添加以下依赖项:
```
dependencies {
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
implementation 'com.google.android.material:material:1.2.1'
}
```
2. 创建一个ViewModel类,该类将处理与UI无关的数据逻辑。例如:
```
import androidx.lifecycle.ViewModel;
public class MyViewModel extends ViewModel {
private int count = 0;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public void incrementCount() {
count++;
}
}
```
3. 创建一个Activity或Fragment类,该类将处理UI逻辑。例如:
```
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
final TextView countTextView = findViewById(R.id.count_text_view);
countTextView.setText(String.valueOf(viewModel.getCount()));
findViewById(R.id.increment_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewModel.incrementCount();
countTextView.setText(String.valueOf(viewModel.getCount()));
}
});
}
}
```
4. 创建一个布局文件,该文件将定义UI元素。例如:
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/count_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:text="0"
android:layout_gravity="center_horizontal"/>
<Button
android:id="@+id/increment_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Increment"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
```
阅读全文