मैं एंड्रॉइड में फ्रैगमेंट सीखने की कोशिश कर रहा हूं और विभिन्न उदाहरणों से मैंने पाया है कि ऐसा करने के विभिन्न तरीके हैं और मैं सिर्फ कुछ सलाह लेना चाहता हूं कि सही तरीका कौन सा है, या कम से कम परिस्थितियों में एक तरीका दूसरे पर इस्तेमाल किया जाना चाहिए।एंड्रॉइड फ्रैगमेंट्स को मुझे 1 खंड का पुन: उपयोग करना चाहिए या नए उदाहरण बनाना चाहिए?
एक उदाहरण ने एक लेआउट बनाया जिसमें एक टुकड़ा और फ्रेमलाउट था। कोड में, जब सूचीफ्रेममेंट से कोई आइटम चुना जाता है तो एक नया टुकड़ा बनाया जाता है (कुछ डेटा के साथ इसे कन्स्ट्रक्टर में आवश्यक होता है) और फ्रेमलेआउट को इस नए टुकड़े के साथ बदल दिया जाता है (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);
}
}