Essential Guide to Android Activities and Fragments
Creatnig an Activity in Android
- Extend the Activity class or its subclasses
- Declare the Activity in AndroidManifest.xml
- Create a layout and set it in Activity's onCreate method
Example manifest declaration:
<activity
android:name=".TestActivity"
android:exported="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Activity Lifecycle Methods
Key lifecycle callbacks:
Starting:
onCreate -> onStart -> onResume
Background:
onPause -> onStop
Returning:
onRestart -> onStart -> onResume
Exiting:
onPause -> onStop -> onDestroy
Activity Launch Modes
Four launch modes defined in manifest:
- standard (default) - Creates new instance each time
- singleTop - Reuses if already at top of stack
- singleTask - Reuses if exists in stack, clears above
- singleInstance - Global singleton in separtae stack
Example singleTop implementation:
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:exported="true">
</activity>
Fragment Fundamentals
Key characteristics:
- Has independent lifecycle
- Depends on host Activity
- Can be retrieved via FragmentManager
Basic fragment creation:
public class SampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_sample, container, false);
}
}
Fragment Communication Patterns
- Public Methods:
// In Activity
public void updateData(String data) { /*...*/ }
// In Fragment
((HostActivity) getActivity()).updateData("New data");
- Interface Callbacks:
// In Fragment
public interface DataListener {
void onDataReceived(String data);
}
// In Activity
public class MainActivity implements SampleFragment.DataListener {
@Override
public void onDataReceived(String data) { /*...*/ }
}
Fragment Back Stack Management
Proper back stack handling:
getParentFragmentManager().beginTransaction()
.hide(currentFragment)
.add(R.id.container, newFragment)
.addToBackStack(null)
.commit();