Ejemplo de LiveData

Ejemplo de uso de LiveData

Descripción general de LiveData

Código en Github: LiveData Demo Project

 

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:layout_marginTop="64dp"
        android:text="0"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textSize="40sp"
        app:layout_constraintBottom_toTopOf="@+id/editText"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberSigned"
        android:text="10000"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="@color/purple_500"
        app:layout_constraintBottom_toTopOf="@+id/startButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/startButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="156dp"
        android:text="Start"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textSize="40sp"
        app:layout_constraintBottom_toTopOf="@+id/stopButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.529"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/stopButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="236dp"
        android:text="Stop"
        android:textAllCaps="false"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textSize="40sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.535"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="1.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivityViewModel.java

public class MainActivityViewModel extends ViewModel {

    CountDownTimer timer;

    private MutableLiveData<Long> seconds = new MutableLiveData<>();
    private MutableLiveData<Boolean> finished = new MutableLiveData<>();
    private MutableLiveData<Long> timerValue = new MutableLiveData<>();

    //public  MainActivityViewModel() {
    //    startTimer();
    //}

    public LiveData<Long> getSeconds() {

        return seconds;
    }

    public LiveData<Boolean> getFinished() {
        return finished;
    }

    public void setTimerValue(Long t) {

        timerValue.setValue(t);
    }

    public void  startTimer() {
        finished.setValue(false);
        //timer = new CountDownTimer(10000, 1000) {
        timer = new CountDownTimer(timerValue.getValue(), 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long timeLeft = millisUntilFinished / 1000;
                seconds.postValue(timeLeft);
            }

            @Override
            public void onFinish() {
                finished.postValue(true);

            }
        };
        timer.start();
    }

    public void stopTimer() {
        timer.cancel();
    }
}

MainActivity.java

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.startButton.setOnClickListener(this);
        binding.stopButton.setOnClickListener(this);

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

        subscribe();

        // viewmodel.startTimer();

    }

    @Override
    public void onClick(View view) {
        if (view == binding.startButton) {
            String text = binding.editText.getText().toString();
            if (text.isEmpty() || text.length() < 4) {
                showMessage("Invalid number, length < 4 digits");
            } else {
                viewmodel.setTimerValue(Long.parseLong(text));
                viewmodel.startTimer();
            }

        }

        if (view == binding.stopButton) {
            viewmodel.stopTimer();
            binding.textView.setText("0");
        }
    }

    private void subscribe() {
        final Observer<Long> secondsObserver = new Observer<Long>() {
            @Override
            public void onChanged(@Nullable final Long s) {
                binding.textView.setText(String.valueOf(s));
            }
        };

        final Observer<Boolean> finishedObserver = new Observer<Boolean>() {

            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean)
                    showMessage("Finished!");
            }
        };

        viewmodel.getSeconds().observe(this, secondsObserver);

        viewmodel.getFinished().observe(this, finishedObserver);
    }

    private void showMessage(String message) {

        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}

 

 

Deja una respuesta