Communication between Fragment and Activity

Asked

Viewed 660 times

8

I’m making an Android app that uses time and date switches (Datepicker and Timepicker), which are displayed in the form of Fragments. When the user sets the desired time, I need it to be passed from the selector Fragment to the main window. I have the following codes:

Fragment of time selector:

package pickers;

import java.util.Calendar;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;

import compromissos.Tela_Cadastro;

public class TimePicker extends DialogFragment implements
        TimePickerDialog.OnTimeSetListener {

    public TimePicker() {
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    @Override
    public void onTimeSet(android.widget.TimePicker view, int hourOfDay,
            int minute) {
        // aqui que eu preciso que a hora selecionada seja enviada para a classe
        // princpal

    }

}

And that of the class that calls the time Fragment:

package compromissos;

import pickers.TimePicker;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import classes.BancoDeDados;
import classes.Evento;

import com.bravosix.compromissos.R;

public class Tela_Cadastro extends Activity {

    BancoDeDados bd = new BancoDeDados(this);
    private EditText nome, data, local, telefone;

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

        nome = (EditText) findViewById(R.id.cadastro_input_evento);
        local = (EditText) findViewById(R.id.cadastro_input_local);
        data = (EditText) findViewById(R.id.cadastro_input_data);
        telefone = (EditText) findViewById(R.id.cadastro_input_telefone);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_cadastro, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {

        switch (item.getItemId()) {

        case R.id.cadastrar:
            salvarEvento();
            return true;

        case R.id.cancelar:
            finish();
            return true;

        default:
            return super.onMenuItemSelected(featureId, item);
        }
    }

    public void mostrarDatePicker(View view) {
        DialogFragment newFragment = new TimePicker();
        newFragment.show(getFragmentManager(), "timePicker");
    }

    public void salvarEvento() {

        String evento_nome, evento_local, evento_data, evento_telefone;

        evento_nome = nome.getText().toString();
        evento_local = local.getText().toString();
        evento_data = data.getText().toString();
        evento_telefone = telefone.getText().toString();

        bd.adicionarEvento(new Evento(evento_nome, evento_local, evento_data,
                evento_telefone));

        Toast.makeText(this, "Evento criado com sucesso.", Toast.LENGTH_SHORT)
                .show();
        finish();
    }
}

I did some research but I didn’t come up with any way that would allow me to do it simply. I read that I could call a static method in the main class, but I need to make a Toast, which requires the context, which I couldn’t get inside a static method. What they suggest to me?

1 answer

8


This is the way I usually do.

In the class of DialogFragment declare an interface defining the methods that the Activity, what he calls the Fragment, should be implemented to be notified of what is happening in the Fragment.

public interface TimeSetListener {
      public void onTimeSet(int hora, int minuto);
}  

I declare a field in DialogFragment to store the reference of Activity who calls the Fragment.

TimeSetListener mListener;  

At the event onAttachof DialogFragment I hold the reference of Activity, it has to implement the interface.

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (TimeSetListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
            + " deve implementar TimeSetListener");
        }
    }  

When I want to inform the Activity call the respective interface method.

@Override
public void onTimeSet(android.widget.TimePicker view, int hourOfDay,
        int minute) {
    mListener.onTimeSet(hourOfDay, minute);
}
  • Thanks, it worked perfectly! Maybe you can ask me the following question: how do I use the 24h format? (I couldn’t find where to declare is24HourView)

  • 1

    If you want to use the 24h format regardless of how it is set in the preferences of device pass true instead of DateFormat.is24HourFormat(getActivity()) in the builder of TimePickerDialog. The function DateFormat.is24HourFormat returns true or false according to what is defined in the preferences.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.