我有两个editText视图,当用户单击第一个editText时,会打开一个对话框碎片窗口,用户选择日期。第二个editText也是如此。所选日期应该在editText中“写入”。当我有一个editText时,这就像一个魅力。但是我怎么知道点击了哪个ediText,因为它们在同一个活动中,我必须在dialogFragment类中编辑editText?
我已经看到了其他一些答案,但其中一些确实已过时 - 已弃用,其他一些并没有帮助我。
这是我的代码:
开始上课:
public class Start extends FragmentActivity {
private EditText ddEdit;
private EditText adEdit;
int year;
int month;
int day;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
public void showDatePickerDialog(View v) {
switch (v.getId()) {
//i know this is not correct
case R.id.etDepDate:
DialogFragment depFragment = new DatePick();
depFragment.show(getFragmentManager(), "datepicker1");
break;
case R.id.etArrDate:
DialogFragment arrFragment = new DatePick();
arrFragment.show(getFragmentManager(), "datepicker2");
break;
}
}
DatePick类:
public class DatePick extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
private EditText ddEdit;
private EditText adEdit;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
String date = new String(day + "/" + (month + 1) + "/" + year);
//????
//how I know here which view was clicked so I can call the editTextById method?
//??????
}
public void editTextById(View v, String date) {
switch (v.getId()) {
case R.id.etDepDate:
setDate(date, ddEdit);
setDate(date, adEdit);
break;
case R.id.etArrDate:
setDate(date, adEdit);
break;
}
}
public void setDate(String date, EditText editText) {
editText.setText(date);
}
@Override
public void show(FragmentManager manager, String tag) {
// TODO Auto-generated method stub
super.show(manager, tag);
}
}
答案 0 :(得分:1)
为每个编辑文本添加一个标志,并更改标记onclick()
答案 1 :(得分:1)
使用newInstance(viewToBeEdited)创建对话框时可以传递视图 在showDatePickerDialog中以这种方式修改对话框的创建
public void showDatePickerDialog(View v) {
depFragment = DatePick.newInstance(v);
depFragment.show(getFragmentManager(), "datepicker1");
break;
}
您的DatePick对话框必须实现静态方法newInstance(Viev v)
public class DatePick extends DialogFragment implements DatePickerDialog.OnDateSetListener {
private EditText editableView;
public static DatePick newInstance(View v) {
DatePick dialog = new DatePick();
dialog.editableView = v;
return dialog;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
<Your code>
}
public void onDateSet(DatePicker view, int year, int month, int day) {
final String date = new String(day + "/" + (month + 1) + "/" + year);
getActivity().runOnUIThread(new Runnable() {
public run() {
editableView.setText(date);
}
});
}
}
我没有测试它,所以可能会有一些拼写错误,但这通常是我在这些情况下所做的。