我在SO上看到了很多关于Fragment的问题,但我仍然无法弄清楚我想做的事情是否可行,更重要的是,我的设计模式是否有缺陷并且需要重新制定整个流程。基本上,就像已经提出的大多数问题一样,我有一个带有导航选项卡的ActionBar(使用ActionBarSherlock),然后在每个选项卡中有一个FragmentActivity,当选择一行时,FragmentActivities会推送新的Fragments(我正在尝试在Android中重新创建一个iOS项目,它只是一个基本的基于导航的应用程序,其中某些选项卡可以深入到特定信息中)。当我点击手机上的返回按钮时,会加载上一个Fragment,但该Fragment会重新创建(因此对于每个视图都会再次调用WebServices),这是不必要的,因为在向后移动时先前视图中的信息不会更改。所以基本上,我想弄清楚的是,如何设置我的Fragments,以便在按下手机的返回按钮时,只需拉起先前的Fragment,并已经创建好了旧的项。以下是我的当前代码:
//This is from my FragmentActivity Class that contains the ActionBar and Tab Selection Control
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
int selectedTab = tab.getPosition();
if (selectedTab == 0) {
SalesMainScreen salesScreen = new SalesMainScreen();
ft.replace(R.id.content, salesScreen);
}
else if (selectedTab == 1) {
ClientMainScreen clientScreen = new ClientMainScreen();
ft.replace(R.id.content, clientScreen);
}.....
//This is within the ClientMainScreen Fragment Class, which handles moving to the Detail Fragment
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Do something if Row is clicked
try{
String selectedClientName = clientObject.getString("ClientName");
String selectedClientID = clientObject.getString("ClientID");
String selectedValue = clientObject.getString("ClientValue");
transaction = getFragmentManager().beginTransaction();
ClientDetailScreen detailScreen = new ClientDetailScreen();
detailScreen.clientID = selectedClientID;
detailScreen.clientName = selectedClientName;
detailScreen.clientValue = selectedValue;
int currentID = ((ViewGroup)getView().getParent()).getId();
transaction.replace(currentID,detailScreen);
transaction.addToBackStack(null);
transaction.commit();
}
catch (Exception e) {
e.printStackTrace();
}
}
});....
//And then this is the Client Detail Fragment, with the method being called to Call the Web Service and create thew (since what is displayed on this screen is dependent on what is found in the Web Service
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved) {
return inflater.inflate(R.layout.clientdetailscreen, group, false);
}
@Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Setup Preferences File Link
this.preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
//initialize the table object
mainTable = (TableLayout)getActivity().findViewById(R.id.mainTable);
//setup the detail table
setupRelatedClientSection();
}
客户详细信息屏幕可以再次进行深入,使用与客户主屏幕相同的方法,但是当我从那个新屏幕返回到详细信息屏幕时,seuptRelatedClientSection() 方法再次被调用,因此整个片段被重建,而我只想打开保存的版本。我的当前设置是否支持这种可能性,还是我方法有误?