我正在尝试制作一个简单的提醒应用程序。创建新提醒时,我有以下设置:
- MainEditActivity.java:以下片段的 2 个占位符 FrameLayouts:
- 编辑名称片段.java
- 自定义操作栏(取消、确定按钮)
- 提醒名称的 EditText
- CheckBox 切换以下片段之一
- EditDateFragment.java 或 EditLocationFragment.java(两者都有很多视图)
- 编辑名称片段.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)
}
编辑名称片段.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 个包含所有元素的 MainActivity 和一个 ViewFlipper。然后我读到片段更好,最终更好地适应平板电脑。这是布置这个的正确方法吗?
问题:我知道如何从EditNameFragment.java获取数据。但是如何获取用户从EditDataFragment或EditLocationFragment输入的数据?我是否需要 MainActivity 中这两个片段的实例来访问它们的视图?还是我需要像使用 EventHandler 一样的另一个回调?如果是,规则是否为每个片段都有一个回调?
我想我在这些组件之间的通信流上有点挣扎。而且我知道片段到片段的通信不是一个好的设计