Generalidades

onSavedInstanceState y onRestoreInstanceState | Medio

¿Qué son onSavedInstanceState () y onRestoreInstanceState () en la actividad?

Hussein Ozkoc
1*US3dF kBFkgeduMzqLJaRw
Ejemplos de onSavedInstanceState y onRestoreInstanceState
public class MainActivity extends AppCompatActivity 

private TextView textView;
private Button button;
private int counter;

@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
textView = findViewById(R.id.counter);
button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
counter = counter + 1;
textView.setText("Counter: " + counter);


);


@Override
public void onSaveInstanceState(Bundle outState)
super.onSaveInstanceState(outState);
outState.putInt("counter", counter);
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
super.onRestoreInstanceState(savedInstanceState);
counter = savedInstanceState.getInt("counter", 0);

¡Magia!

Ejemplos de onSavedInstanceState y onRestoreInstanceState
package com.example.customview_example;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity

private TextView textView;
private Button button;
private int counter = 0;

@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView = findViewById(R.id.counter);
button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
counter = counter + 1;
textView.setText("Counter: " + counter);


);

@Override
public void onSaveInstanceState(Bundle outState)
super.onSaveInstanceState(outState);
outState.putInt("counter", counter);

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
super.onRestoreInstanceState(savedInstanceState);
counter = savedInstanceState.getInt("counter", 0);
textView.setText("Counter: " + counter);

Foto de Timothy Meinberg en Unsplash

LEER  El dispositivo de transmisión Onn FHD de Walmart es como un Chromecast más barato

Publicaciones relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Botón volver arriba