나는 안드로이드에서 단편을 배우려고 노력하고 있는데, 여러 가지 예를 들어 보니 여러 가지 방법이있을 것 같았고 올바른 방법 또는 적어도 상황에 따라 한 가지 방법으로 조언을 얻고 싶었습니다. 다른 것보다 사용해야합니다.Android Fragments는 조각을 다시 사용하거나 새 인스턴스를 만들어야하나요?
하나의 예는 조각과 FrameLayout을 포함하는 레이아웃을 만들었습니다. 코드에서 ListFragment에서 항목을 선택하면 생성자에서 필요한 일부 데이터가있는 새 조각이 만들어지고 FrameLayout은 FragmentTransaction.replace()를 사용하여이 새 조각으로 바뀝니다.
또 다른 예는 2 개의 프래그먼트를 나란히 배치하는 레이아웃 파일을 가지고 있습니다. 이제 코드에서 사용자가 하나의 조각에서 목록의 항목을 선택하면 데이터를 업데이트하기 위해 (선택한 항목을 기반으로) 다른 조각으로 전화가 걸립니다.
그래서 나는이 방법들 중 하나가 다른 것보다 선호되는지, 아니면 특정 상황을 사용해야하는지 궁금하다.
편집 :
1 :
mCurCheckPosition = index;
if (mDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);
// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment)
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
2 : 그래서
public void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
DetailFragment fragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detailFragment);
if (fragment != null && fragment.isInLayout()) {
fragment.setText(item);
} else {
Intent intent = new Intent(getActivity().getApplicationContext(),
DetailActivity.class);
intent.putExtra("value", item);
startActivity(intent);
}
}