Android - Pasar fecha desde fragmento hasta activity y mostrarlo en textview.

 
Vista:

Pasar fecha desde fragmento hasta activity y mostrarlo en textview.

Publicado por bladimirs (3 intervenciones) el 26/03/2016 14:13:21
Hola a todos. Estoy realizando una aplicacion donde el usuario al pulsar un boton aparece un fragmeto con un datepicker. La activity que genera el fragmento, ademas de poseer el boton ya mencionado, muestra un textview. Al seleccionar la fecha deseada esta debe aparecer en ese textview. El asunto es que no se como hacerlo. El codigo de la clase principal es el siguiente:



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
public class Seleccionarcentro extends FragmentActivity implements
        TwoActionButtonsDialog.DialogListener {
    // If you're using Android API 11 o lower, your Activity must extend
    // FragmentActivity
    private SQLiteDatabase baseDatos;
    private static final String nombreBD = "Guardias";
     private static final String TAGG = "bdguardias";
     private Cursor c;
     Context context;
    private static final String TAG = "dialog";
    private static final int SIZE_DOWNLOAD = 255;
 
    private boolean mIsLargeLayout;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        mIsLargeLayout = getResources().getBoolean(R.bool.large_layout);
        llenarspn1();
         TextView txtvw2 = (TextView) findViewById(R.id.txtvw2);
    }
 
    private void llenarspn1() {
        // TODO Auto-generated method stub
        try {
            Spinner spn1 = (Spinner)this.findViewById(R.id.spn1);
            baseDatos = openOrCreateDatabase(nombreBD, MODE_WORLD_WRITEABLE, null);
            Cursor cur = baseDatos.rawQuery("select codigo AS _id, nombre from centros ORDER BY nombre ASC", (String[])null);
            startManagingCursor(cur);
            String[] from = new String[] { "nombre" };
             int[] to = new int[] { android.R.id.text1 };
             SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, cur, from, to);
             mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
             spn1.setAdapter(mAdapter);
            }
            catch (Exception e)
            {
              Log.i(TAGG, "Error al abrir o crear la base de datos" + e);
            }
    }
 
    public void showDialog() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        CustomDialog newFragment = new CustomDialog();
 
        if (mIsLargeLayout) {
            // The device is using a large layout, so show the fragment as a
            // dialog
            newFragment.show(fragmentManager, TAG);
        } else {
            // The device is smaller, so show the fragment fullscreen
            FragmentTransaction transaction = fragmentManager
                    .beginTransaction();
            // For a little polish, specify a transition animation
            transaction
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            // To make it fullscreen, use the 'content' root view as the
            // container for the fragment, which is always the root view for the
            // activity
            transaction.add(android.R.id.content, newFragment)
                    .addToBackStack(null).commit();
        }
    }
    public void showCustomDialog(View v) {
        DialogFragment dialog = new CustomDialog();
        dialog.show(getSupportFragmentManager(), TAG);
    }
    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), TAG);
    }
 
}

Y la clase que genera el fragmento es la siguiente:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {
 Context context;
 public static String dia, mes, ano;
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
 
        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }
 
 
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        dia = String.valueOf(dayOfMonth);
        mes = String.valueOf(monthOfYear);
        ano = String.valueOf(year);
 
    }
}

Al final le asigno valor a tres variables pulbicas, pero este metodo no me funciona porque la actividad seleccionarcentro se crea antes del fragmento.

Cualquier ayuda sera apreciada. Saludos.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 112
Bronce
Ha disminuido 1 puesto en Android (en relación al último mes)
Gráfica de Android

Pasar fecha desde fragmento hasta activity y mostrarlo en textview.

Publicado por Yamil Bracho (100 intervenciones) el 26/03/2016 16:11:27
1) crea un metodo en tu actividad, digamos setFecha que reciba los datos del fragmento
2) dentro de tu fragmento crea una referencia a tu actvidad en el onCreateView, algo como
MiActividad activity;
....
OnCreateView
activity = (MuActividad) getActivity();


Cuando quieras pasar el dato a tu actvidad
activity.setFecha(tuFecha)
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar