Activate a button from another class in Android Studio

1

I have two classes, one is called Frame1 and the other is Frame2. Frame2 has a button that is disabled, what I want is to press the Frame1 button so that the button of the other class activates me, since while I do not press the button 1, the button 2 must not be enabled by anything in the world. I would like to know how it is possible to achieve it, because up to now I get an error.

This is my Frame1 layout:

This is the code of Frame1:

public class Frame1 extends AppCompatActivity implements View.OnClickListener {

public Button frame1btn;

public Frame2 f;

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

    f = new Frame2();

    frame1btn = (Button)findViewById(R.id.botonframe1);
    frame1btn.setOnClickListener(this);
}

@Override
public void onClick(View v) {

    f.frame2btn.setEnabled(true);
}

This is the layout of Frame2:

This is the code for Frame2:

public class Frame2 extends AppCompatActivity implements View.OnClickListener {

public Button frame2btn;

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

    frame2btn = (Button)findViewById(R.id.botonframe2);
    frame2btn.setOnClickListener(this);
}


@Override
public void onClick(View v) {

    Toast.makeText(this, "Lo lograste!", Toast.LENGTH_SHORT).show();
}

I appreciate the help in advance.

    
asked by Milagros 18.11.2018 в 23:44
source

1 answer

0

This can be done with Shared Preferences (SP). In onCreate of activity 1:

 final SharedPreferences sharedPref = getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
 //sharedPref.edit().clear().apply();  // opcional si quieres que inicie como desabilitado el botón cada vez que se cree la activity

        @Override
        public void onClick(View v) {
            // llamas al editor del SP
            SharedPreferences.Editor editor = sharedPref.edit();
            //colocas una clave (botón) con su valor(activar), luego commit o apply para que se guarde ese valor en SP
            editor.putString("boton", "activar");
            editor.commit();
        }
    });

In onCreate of activity 2 you get the value of the sp:

  // llamas a SP:
 SharedPreferences sharedPref = getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
  // luego creas un String con el valor que guardastes del key(boton), en caso de
  // que no hayas guardado nada tomara el valor por default, en este caso "nada"
 String clave = sharedPref.getString("boton", "nada");
  // y comparas el resultado para activar o no el botón:
  if("activar".equals(clave)) {
        frame2btn.setEnabled(true);
    }else {
        frame2btn.setEnabled(false);
    }
    
answered by 19.11.2018 / 03:10
source