选择时间后,我有一个TimePickerFragment和一个onTimeSet来执行操作。问题是,我有两个按钮来选择时间,而且我不知道如何知道哪个用户使用过。我尝试了一个开关,但是cannot resolve symbol
。
有什么主意如何知道用户选择哪个按钮?
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;
}
}
我的按钮:
<Button
android:id="@+id/button"
...
/>
<Button
android:id="@+id/button2"
...
/>
mainActivity(总结)
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");
}
答案 0 :(得分:1)
您可以使TimePickerFragment的构造函数采用视图ID。 在您的主要活动中:
DialogFragment newFragment = new TimePickerFragment(v.getId());
在您的TimePickerFragment中:
private String viewId;
public TimePickerFragment(String viewId) {
super();
this.viewId = viewId;
}
答案 1 :(得分:1)
您可以将片段添加到片段中。
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
Bundle args = new Bundle();
args.putString("","");
newFragment.setArguments(args);
newFragment.show(getSupportFragmentManager(), "timePicker");
}
然后在您的片段类中,您可以使用
Bundle args = getArguments();
args.getString("","");
由于我目前无法测试语法,因此您需要进行适当的更改。但这是如何将参数分成片段的一般想法。