Search code examples
javaandroiddialogfragment

How to get id of a view that opened a DialogFragment?


I add a onClick method to various EditTexts. It opens a DialogFragment.


public void eligeHora (View view){
        TimePickerFragment newFragment = new TimePickerFragment();
        newFragment.show(getFragmentManager(),"hadshads");
    }

Now, inside the DialogFragment class I want to get the id of THE EditText clicked (there are many). In this example I get the EditText with the id "hora", but I want it "generic".


public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){

        //Create and return a new instance of TimePickerDialog
        return new TimePickerDialog(getActivity(),this, 0, 0,
                true);
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//Do something with the user chosen time
        //Get reference of host activity (XML Layout File) TextView widget
        EditText tv =  getActivity().findViewById(R.id.hora);

        tv.setText(String.valueOf(hourOfDay)+ " : " +
                String.valueOf(minute) + "\n");
    }

}

How do I get the id of the view clicked to open the DialogFragment? In the example I used the id of a specific view (R.id.hora), but I want to be able to use this fragment with all the views that have the method eligeHora.


Solution

  • You can pass the id to the Fragment not via the Constructor but by using a static method:

    public static TimePickerFragment instance(int viewId){
        TimePickerFragment fragment = new TimePickerFragment();
        Bundle b = new Bundle();
        b.putInt("KEY_ID", viewId);
        fragment.setArguments(b);
        return fragment;
    }
    

    Instead of

    TimePickerFragment newFragment = new TimePickerFragment();
    

    you'd have to write

     TimePickerFragment newFragment = TimePickerFragment.instance(myEditTextID);
    

    Later on, you can retrieve the id like this:

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        int id = getArguments().getInt("KEY_ID");
        //...
    }
    

    But be aware that it's not a good idea to access Views ´from within the Fragment which are not part of the Fragment. Consider using an interface to communicate with the Activity