Thursday, 2 April 2020

Android ViewModel concept | Understand the basic concept of viewModel with a simple example.

Questions:-
I will make a score adding and resting the score to 0 example.To understand the basic concept of a view model  first i will create a normal way to do the problem.

1. I used data binding concept here so for that i have used below line of code in app gradle file:-
dataBinding {
        enabled = true
    }
2. Now  create the UI first, activity.main.xml-
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/score"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginBottom="30dp"
            android:text="0"
            android:textSize="40sp" />

        <Button
            android:id="@+id/start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/score"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="20dp"
            android:background="@color/colorAccent"
            android:text="Start"
            android:textColor="#ffffff" />

        <Button
            android:id="@+id/reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/start"
            android:layout_centerHorizontal="true"
            android:text="reset" />

    </RelativeLayout>
</layout>

3. MainActivity.java
public class MainActivity extends AppCompatActivity {
    private int num = 0;

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        binding.start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addScore();
            }
        });

        binding.reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetValue();
            }
        });
    }

    private void addScore() {
        num++;
        binding.score.setText(String.valueOf(num));
    }

    private void resetValue() {
        num = 0;
        binding.score.setText(String.valueOf(num));
    }
}
############################
-----------------Same example viewModel----------

----------------MainActivityViewModel.java-------------------
package com.example.androidviewmodelbasicex;
import androidx.lifecycle.ViewModel;
public class MainActivityViewModel extends ViewModel {
    private Integer score = 0;
    public Integer getScore() {
        if (score == null)
            score = 0;
        return score;
    }

    public void setScore() {
        score++;
    }
    public void resetScore() {
        score = 0;
    }
}
-----------------MainActivity.java------------------
package com.example.androidviewmodelbasicex;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.view.View;
import com.example.androidviewmodelbasicex.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
      private ActivityMainBinding binding;
    private MainActivityViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        viewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);

        binding.score.setText(String.valueOf(viewModel.getScore()));
        binding.start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.setScore();
                binding.score.setText(String.valueOf(viewModel.getScore()));
            }
        });
        binding.reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.resetScore();
                binding.score.setText(String.valueOf(viewModel.getScore()));
            }
        });
    }
}


No comments:

Post a Comment