3

我有兩個類。一個是我的主要活動,另一個是應該打開Android DatePicker的助手方法。到目前爲止一切正常,除非我想從日期選擇器類中檢索日期。這裏是我的課:公共方法在同一包中的其他類不可見

// This is the class that creates the date picker 
    package com.strom.myapp; 

    import android.app.DatePickerDialog; 
    import android.app.Dialog; 
    import android.app.DialogFragment; 
    import android.os.Bundle; 
    import android.widget.DatePicker; 

    import java.util.Calendar; 



    public class DefaultDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener { 

     private String returnDate; 


     public String getReturnDate() { 
      return returnDate; 
     } 

     @Override 
     public Dialog onCreateDialog(Bundle savedInstanceState) { 
      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); 

      return new DatePickerDialog(getActivity(), this, year, month, day); 
     } 

     @Override 
     public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 
      returnDate = String.valueOf(dayOfMonth) + 
        "." + 
        String.valueOf(monthOfYear) + 
        "." + 
        String.valueOf(year) + 
        ", 00:00"; 
     } 
    } 

,這裏是主要的活動

package com.strom.myapp; 

import android.app.DialogFragment; 
import android.content.Context; 
import android.content.SharedPreferences; 
import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.TextView; 

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 


public class BalanceScreen extends ActionBarActivity { 

private String payDate; 

// ... omitted code ... 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     if (id == R.id.action_payDate) { 

      DialogFragment datePicker = new DefaultDatePicker(); 
      datePicker.show(getFragmentManager(), "datePicker"); 
      payDate = datePicker.getReturnDate(); 

      return true; 
     } 


// ... omitted code ... 

} 

吸氣法 'datePicker.getReturnDate();'不能從主要活動中獲得,即使它們在同一個包中。我不明白爲什麼這不應該工作。我在這裏錯過了什麼?

回答

5

我會建議你更換:

DialogFragment datePicker = new DefaultDatePicker(); 

DefaultDatePicker datePicker = new DefaultDatePicker(); 

因爲你的方法getReturnDate在DefaultDatePicker宣佈,而不是在DialogFragment。

+1

這,我是太慢了。 –

0

你可以施放datePicker(其中refeers DefaultDatePicker的實例)DefaultDatePicker調用所特有的DatePickerDialog.OnDateSetListener方法。

((DefaultDatePicker)datePicker).getReturnDate() 
0

添加公共變量您的活動說

public String dateFromPicker = ""; 

DefaultDatePicker方法onDateSet做到這一點

((BalanceScreen)getActivity()).dateFromPicker = returnDate; 
相關問題