我在試圖製作一個簡單的提醒應用程序。當創建一個新的提醒,我有以下設置:片段與活動之間的通信流程
- MainEditActivity.java:2佔位FrameLayouts以下片段:
- EditNameFragment.java
- 自定義操作欄(取消, OK按鈕)
- 提醒名稱的EditText
- CheckBox切換下列其中一個片段
- EditDateFragment.javaOREditLocationFragment.java(兩者有很多的意見)
- EditNameFragment.java
MainEditActivity.java:
private LocationFragment mLocationFragment;
private DateFragment mDateFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_remainer_main); // 2 frame layouts
if (savedInstanceState == null) {
Fragment newFragment = new NewReminderFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.reminder_title_fragment, newFragment).commit();
mDateFragment = new DateFragment();
ft = getFragmentManager().beginTransaction();
ft.add(R.id.date_or_location_fragment, mDateFragment).commit();
}
}
public void onCheckBoxClick(View view)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(mLocationFragment == null)
mLocationFragment = new LocationFragment();
CheckBox checkBox = (CheckBox)findViewById(R.id.checkBoxID);
if(checkBox != null)
{
if(checkBox.isChecked()) {
fragmentTransaction.replace(R.id.date_or_location_fragment, mLocationFragment);
} else {
fragmentTransaction.replace(R.id.date_or_location_fragment, mDateFragment);
}
fragmentTransaction.commit();
}
@Override
public void handleEvent(EventInfo event) {
// here I get all the data (name, data, time, location, etc)
}
EditNameFragment.java:
private EventHandler mEventHandler;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mEventHandler = (EventHandler)activity;
}
View doneButton = actionBarButtons.findViewById(R.id.doneBtnTextID);
doneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createNewReminder();
}
});
private void createNewReminder()
{
// Event info object to store all information (reminder name, data, time, etc)
EventInfo eventInfo = new EventInfo();
// access either Date or Location Fragment (depending on which is visible)
// FIXME: access the fragments and get the data
// let the activity know to display the new reminder
mEventHandler.handleEvent(eventInfo);
}
問:我開始只使用1與所有元素和ViewFlipper MainActivity。然後我看到片段更適合最終適應平板電腦。這是解決這個問題的正確方法嗎?
問題:我知道如何從獲取數據EditNameFragment.java。但是,如何獲取用戶從EditDataFragment或EditLocationFragment輸入的數據? 我需要MainActivity中這兩個片段的實例來訪問它們的視圖嗎?還是需要像我在EventHandler上那樣進行另一個回調?如果是的話,規則是要爲每個片段進行回調?
我想我掙扎了一下這些組件之間的通信流。我知道片段到片段通信不是一個好的設計
是的,這是有道理的。所以我首先做出了正確的決定,只使用了1個活動和一個ViewFlipper。至少我現在知道下一次我需要每個片段的回調接口。謝謝! – user2246120 2013-04-04 20:33:34