Android Sdk DatePickerFragment and TextView

前端 未结 1 840
隐瞒了意图╮
隐瞒了意图╮ 2020-12-20 10:32

i got the next problem. I want to pass the date i\'ve entered using my DatePickerFragment to TextView, but i don\'t know how i can actually do it.

相关标签:
1条回答
  • 2020-12-20 11:17

    Your app crashed probably because of this

       TextView tvDate1 = (TextView) getView().findViewByiD(R.id.tvDate);
    

    I guess your picker is in a different file and you are trying to initialize textview. findViewById is a method of activity class

    Use a interface

    http://developer.android.com/guide/components/fragments.html

    Check the topic under communicating with activity

    public class DatePickerFragment extends DialogFragment
    implements DatePickerDialog.OnDateSetListener {
    
        TheListener listener;
    
    public interface TheListener{
        public void returnDate(String date);
    }
    
    @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);
    listener = (TheListener) getActivity(); 
    
    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);
    }
    
    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
    Calendar c = Calendar.getInstance();
    c.set(year, month, day);
    
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String formattedDate = sdf.format(c.getTime());
    if (listener != null) 
    {
      listener.returnDate(formattedDate); 
    
    }
    
    }
    }
    

    Then in MainActivity implement the interface and set the date to textview

    public class MainActivity extends Activity implements DatePickerFragment.TheListener{
    
        Button b;
        TextView tv;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            b= (Button) findViewById(R.id.button1);
            tv= (TextView) findViewById(R.id.textView1);
            b.setOnClickListener(new OnClickListener()
            {
    
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    DialogFragment picker = new DatePickerFragment();
                    picker.show(getFragmentManager(), "datePicker");
                }
    
            });
        }
    
        @Override
        public void returnDate(String date) {
            // TODO Auto-generated method stub
            tv.setText(date);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题