Reputation: 4253
I have a TimePickerFragment and a onTimeSet to do an action after select the time. The problem is, I have two buttons to select time and I don't know how to know which one user used. I tried a switch but it cannot resolve symbol
.
any ideas how to know which button user select?
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
...
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
switch(view) {
case R.id.bstart: //cannot resolve symbol
Toast.makeText(Objects.requireNonNull(getActivity()).getApplicationContext(), "button 1", Toast.LENGTH_SHORT).show();
break;
case R.id.bend:
Toast.makeText(Objects.requireNonNull(getActivity()).getApplicationContext(), "button 2", Toast.LENGTH_SHORT).show();
break;
}
}
my buttons:
<Button
android:id="@+id/button"
...
/>
<Button
android:id="@+id/button2"
...
/>
mainActivity (sum up)
public Button bstart;
public Button bend;
bstart = findViewById(R.id.button);
bend = findViewById(R.id.button2);
bstart.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
showTimePickerDialog(v);
}
});
bend.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
showTimePickerDialog(v);
}
});
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Upvotes: 0
Views: 49
Reputation: 1629
You could add a bundle to your fragment.
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
Bundle args = new Bundle();
args.putString("","");
newFragment.setArguments(args);
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Then in your fragment class you can get the arguments with
Bundle args = getArguments();
args.getString("","");
You will need to make changes appropriately as I could not test the syntax at this time. But that is the general idea of how you can get parameters into a fragment.
Upvotes: 1
Reputation: 721
You can make the constructor for your TimePickerFragment take the view id. In your main activity:
DialogFragment newFragment = new TimePickerFragment(v.getId());
In your TimePickerFragment:
private String viewId;
public TimePickerFragment(String viewId) {
super();
this.viewId = viewId;
}
Upvotes: 1