2014-04-30 40 views
0

當我的應用程序中的菜單項打開datePicker並選擇一個日期時,僅當我再次打開選項菜單時,UI中的textview'selectedDateView'纔會更新。菜單操作完成後更新活動UI

@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_settings) { 

     DialogFragment newFragment = new SettingsDatePicker(); 
     newFragment.show(getFragmentManager(), "Select the date"); 

     // i think this is called only the second time 
     selectedDateView.setText(String.format("Selected Date: %s", settings.getConfiguredDateTime().toString(fmt))); 

     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

有沒有辦法來重寫OnSettingMenuItemFinished或類似的東西?

感謝您的幫助。

+1

在你的dialogfragment中有一個回調,然後當你選擇日期時調用回調。例如:[鏈接](http://stackoverflow.com/questions/9776088/get-data-back-from-a-fragment-dialog-best-practices) – mario

+0

活動佈局中的'selectedDateView'。你可以發佈佈局嗎? – Libin

+0

謝謝@mario 我使用你的建議解決了這個問題:D – BinaryFr3ak

回答

0

解決它使用建議馬里奧告訴我的評論。

**EDIT: Add of Source** 

// Activity which calls the datepicker. I KNOW THAT THE CODE CAN BE IMPROVED! Just for trials. 
public class MyActivity extends Activity 
{ 
    /* 
    * Code blabla 
    */ 
    @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_settings) { 

      DialogFragment newFragment = new SettingsDatePicker(); 
      newFragment.setCallback(this); 
      newFragment.show(getFragmentManager(), "Select the date"); 

      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    public void CallBack(String text) 
    { 
      // i think this is called only the second time 
      selectedDateView.setText(String.format("Selected Date: %s", text)); 
    } 

    /* 
    * Code blabla 
    */ 
} 


// DialogFragment 
public class SettingsDatePicker extends DialogFragment 
{ 

    private MyActivity activity = null; 
    /* 
    * Code blabla 
    */ 
    public void setCallback(MyActivity activity) { 
     //set callback class 
     this.activity = activity; 
    } 

    public void onDateSet(DatePicker view, int year, int month, int day) { 
     // Do something with the date chosen by the user 
     this.activity.CallBack("TextToUpdate"); 
    } 

    /* 
    * Code blabla 
    */ 
} 
+1

如果你發佈你用來解決問題的代碼,它可能會幫助某個人(像我這樣的新手)。 – shanavascet

+0

@shanavascet感謝您的反饋 - 希望它有幫助。 – BinaryFr3ak