Ejemplo de ViewModel

Ejemplo de uso de ViewModel

ViewBinding en build.gradle

buildFeatures {
    viewBinding true
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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/textView"
        android:layout_width="128dp"
        android:layout_height="57dp"
        android:text="0"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textSize="40sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.207" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add +1"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textSize="40sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.129" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivityViewModel

public class MainActivityViewModel extends ViewModel {

    private int number = 0;

    public void addNumber() {
        this.number ++;
    }

    public int getNumber() {
        return  this.number;
    }
}

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener, LifecycleOwner{

    MainActivityViewModel viewmodel;
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        binding.button.setOnClickListener(this);

        viewmodel = new ViewModelProvider(this).get(MainActivityViewModel.class);

        binding.textView.setText(String.valueOf(viewmodel.getNumber()));

    }

    @Override
    public void onClick(View view) {
        if (view == binding.button) {
            viewmodel.addNumber();
            binding.textView.setText(String.valueOf(viewmodel.getNumber()));
        }
    }
}

 

Codelab:

Incorporate Lifecycle-Aware Components

Deja una respuesta