-1

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.

2 Answers2

1

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

Bö macht Blau
  • 12,820
  • 5
  • 40
  • 61
1

The other answer is basically correct: you can pass the view id to the TimePickerFragment by using setArguments(). The only piece it is missing is how to actually get the id of the view that was clicked on.

Assuming that you're using the android:onClick attribute on all of your views, and each of them uses your eligeHora(View view) method...

The View parameter to this method is the view the user clicked on. So you can get the clicked view's id by calling view.getId() inside eligeHora().

Ben P.
  • 52,661
  • 6
  • 95
  • 123