Referencing main class variable in an @Override

1

We can reference a variable of the main class, for example within the method onCreate of the 2 forms (with or without this ):

public class NovoRegistro extends AppCompatActivity {

TextView data, horario;
int dia, mes, ano;

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

       this.data = findViewById(R.id.tvwData);
       horario = findViewById(R.id.tvwHorario);
   }
}

But if I'm inside a superscript method of another class, I can not use this , otherwise it would be pulling from the method's main class.

Example:

public void datePicker(View v) {
        DatePickerDialog dp = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker datePicker, int ano, int mes, int dia) {
                mes = mes + 1;
                String dataSelecionada = (dia + "/" + mes + "/" + ano);
                data.setText(dataSelecionada);
            }
        }, ano, mes, dia);
        dp.show();
    }

In the example above, the onDateSet method is returning me ano, mes, dia just like in my main class.

What would be the best way to set the ano, mes, dia properties of my main class with method properties?

    
asked by anonymous 24.01.2018 / 19:42

1 answer

3

The problem here is that the method variables have the same name as the Activity attributes. Use NovoRegistro.this to access the NewRegistry object (your activity):

NovoRegistro.this.ano = ano;
NovoRegistro.this.mes = mes;
NovoRegistro.this.dia = dia;

this is a reserved word that, in this context, is a reference to the current object. It's like a variable (attribute) that holds the current object. To reference it in an inner class should include the outer class name: NomeDaOuterClasse.this .

Since NovoResgisto.this represents the instance of NewRegistry, you can access all of its members through it.

    
24.01.2018 / 19:50