Solution 1 :
By calling datePicker.getTag()
, you are getting the wrong tag; which is the DatePicker
tag, not the DatePickerFragment
tag.
To see the right tag, just use getTag()
inside your custom DatePickerFragment
getTag() inside my Fragement class works fine. But how to I pass the
tag back to my activity where I called show() My Fragement currently
only contains the onCreateDialog method where I return a new
DatePickerDialog instance
You can pass a listener to your DatePickerFragment
constructor, and trigger its callback with the Fragment tag whenever you set a date.
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
interface OnDateAdjustedListener {
void onDateAdjusted(String tag);
}
private OnDateAdjustedListener mOnDateAdjustedListener;
// Constructor with a Listener
public DatePickerFragment(OnDateAdjustedListener onDateAdjustedListener) {
mOnDateAdjustedListener = onDateAdjustedListener;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// .... Handle onCreateDialog
}
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
// .... Handle onDateSet
// callback with fragment tag
mOnDateAdjustedListener.onDateAdjusted(getTag());
}
}
And in your activity modify the constructor, and implement the interface
public class MainActivity extends AppCompatActivity implements View.OnClickListener, DatePickerFragment.OnDateAdjustedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatePickerFragment dateFragment = new DatePickerFragment(this);
}
@Override
public void onDateAdjusted(String tag) {
Toast.makeText(this, tag, Toast.LENGTH_SHORT).show();
}
}
Problem :
I am opening different date picker fragments in my android app.
The fragement is opened like this.
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "MY_TAG");
The I implemented the onDateSet method which has the picked date and a DatePicker object. Now I tried to get the tag from the DatePicker object to check which picker has been shown.
There is a method datePicker.getTag()
, but this returns null.
Is there a way to get the tag which has been commited in the show method?
Comments
Comment posted by CodingLeo
getTag()