我正在嘗試使用片段創建具有主/明細流的應用程序。選擇一個項目將打開一個細節片段,然後可以打開另一個片段並將其添加到後端堆棧。在主/細節流中切換片段
我已經重新命名了類來幫助說明他們做了什麼。
public class ListOfDetails extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
//Callback method indicating that an item with the given ID was selected.
public void onItemSelected(String id) {
// Performing logic to determine what fragment to start omitted
if (ifTwoPanes()) {
Fragment fragment = new DetailFragmentType1();
getSupportFragmentManager().beginTransaction().replace(R.id.aContainer, fragment).commit();
} else {
Intent newIntent = new Intent(this, SinglePaneFragmentWrapper.class);
newIntent.putExtra("id", id);
startActivity(newIntent);
}
}
// My attempt at making it possible to change displayed fragment from within fragments
public void changeDetailFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.replace(R.id.aContainer, fragment);
transaction.commit();
}
}
其中一個詳細片段的示例。在不同情況下可能會創建許多不同的片段。
public class DetailFragmentType1 extends Fragment {
private ListOfDetails parent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity a = getActivity();
if (a instanceof ListOfDetails) {
parent = (ListOfDetails) a;
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button aButton = (Button) getActivity().findViewById(R.id.aButton);
aButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
parent.changeDetailFragment(new SubDetailFragment());
}
});
}
}
當電話,一個包裝活動是用來裝片段
public class SinglePaneFragmentWrapper extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Duplicate logic must be performed to start fragment
// Performing logic to determine what fragment to start omitted
String id = getIntent().getStringExtra("id");
if(id == "DetailFragmentType1") {
Fragment fragment = new DetailFragmentType1();
getSupportFragmentManager().beginTransaction().replace(R.id.aContainer, fragment).commit();
} else {
...
}
}
}
什麼是改變就是在這種情況下的細節窗格中打開該片段的正確方法?我的方法在使用兩個窗格時感覺像是黑客,並且在僅使用一個窗格時不起作用,因爲來自SinglePaneFragmentWrapper的getParent()
返回null,使我無法呼叫parent.changeDetailFragment()
。
這是一個複雜的問題,希望我解釋得很好。讓我知道如果我錯過了什麼。謝謝