ListAdapter中的TimePickerDialog:已添加片段

时间:2014-03-07 23:00:14

标签: android android-fragments dialogfragment

我有一个动态创建行的列表。每行包含一个EditText,当用户单击此视图时,我希望显示一个TimePickerDialog。我在我的代码中的其他地方使用相同的技术,但不是在ListView中,它工作得很好,但不知怎的,此时我总是得到

ERROR   AndroidRuntime      java.lang.IllegalStateException: Fragment already added: TimePickerDialogFragment{42f06710 #0 0c005225-d6a4-47f9-b3ee-ac90a70d3962}
ERROR   AndroidRuntime      at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1175)
ERROR   AndroidRuntime      at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:616)

我的ListAdapter是:

private class SetAdapter extends BaseAdapter {

        private LayoutInflater inflater = null;        

        public SetAdapter() {
            inflater = LayoutInflater.from(TrainingDetailActivity.this);
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = inflater.inflate(R.layout.training_detail_row, parent, false);
            EditText col1 = (EditText) convertView.findViewById(R.id.trainingDetailCol1);
            setTimePickerTo(col1, exercise.getSets().get(position), UUID.randomUUID().toString());
        }
}

private void setTimePickerTo(EditText editText, final Set set, final String tag) {
        int hours = exercise.getDuration() / 60;
        int minutes = exercise.getDuration() % 60;
        editText.setText(String.format("%02d:%02d", hours, minutes));
        TimePickerDialog.OnTimeSetListener timePickerDurationListener
            = new TimePickerDialog.OnTimeSetListener() {

                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    int val = hourOfDay * 60 + minute;
                    exercise.setDuration(val);
                    notifyDataSetChanged();
                }
            };
        final TimePickerDialogFragment timePickerDuration
                = new TimePickerDialogFragment(exercise, timePickerDurationListener);
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    timePickerDuration.show(getSupportFragmentManager(), tag);
                }
                else {

                }
            }
        });

    }

因为TimePickerDialogFragment在其他地方工作,我猜问题来自ListView。如果我添加

timePickerDuration.dismiss()

到onFocusChange()上的else-case,对话框显示并解散几次,logcat被垃圾邮件

WARN    IInputConnectionWrapper getExtractedText on inactive InputConnection
WARN    IInputConnectionWrapper getTextBeforeCursor on inactive InputConnection
WARN    IInputConnectionWrapper getExtractedText on inactive InputConnection

任何想法我能做什么?

1 个答案:

答案 0 :(得分:0)

试试这个:在适配器类中,在getView()中,在if (convertView == null)

周围放置一个convertView = inflater.inflate(R.layout.training_detail_row, parent, false);条件